package com.cgnpc.framework.service.impl;


import cn.com.cgnpc.aep.bizcenter.appcenter.sdk.client.RestClient;
import cn.com.cgnpc.aep.bizcenter.appcenter.sdk.config.Constants;
import cn.com.cgnpc.aep.bizcenter.appcenter.sdk.result.ApiResult;
import cn.com.cgnpc.aep.bizcenter.appcenter.sdk.vo.CgnRequestHeader;
import cn.com.cgnpc.aep.bizcenter.bpmcenter.api.entity.*;
import cn.com.cgnpc.aep.bizcenter.bpmcenter.api.psc.*;
import cn.com.cgnpc.aep.bizcenter.bpmcenter.api.vo.*;
import cn.com.cgnpc.aep.bizcenter.email.vo.SendEmails;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cgn.psc.entity.bizobj.DelegateSetting;
import com.cgn.psc.entity.callBack.CallBackResult;
import com.cgn.psc.entity.callBack.ExecuteResultType;
import com.cgn.psc.entity.callBack.SubmitActionType;
import com.cgn.psc.entity.iProcInstFlow.*;
import com.cgn.psc.entity.query.QueryDirection;
import com.cgn.psc.entity.query.QueryLogical;
import com.cgn.psc.entity.query.QueryOperator;
import com.cgn.psc.entity.query.QueryPaging;
import com.cgn.psc.entity.query.field.*;
import com.cgn.psc.entity.query.info.ToDoTaskQuery;
import com.cgnpc.cud.boot.autoconfigure.aep.AepProperties;
import com.cgnpc.cud.core.common.util.DateUtils;
import com.cgnpc.cud.core.common.util.MessageUtils;
import com.cgnpc.cuddemo.funcInstance.service.ICudWinService;
import com.cgnpc.framework.service.IBpmCenterService;
import com.cgnpc.framework.service.IEmailCenterService;
import com.cgnpc.framework.userinfo.CurrentUser;
import com.cgnpc.framework.utils.CgnHeader;
import com.cgnpc.scp.common.pojo.UserInfo;
import com.cgnpc.scp.common.utils.BpmUtil;
import com.cgnpc.scp.common.utils.JacksonUtil;
import com.cgnpc.scp.config.MockClient;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/******************************
 * 用途说明: 中台流程相关的处理
 * 作者姓名: pxmwrya
 * 创建时间: 2019/6/17_11:18
 ******************************/
@Slf4j
@Service
public class BpmCenterServiceImpl implements IBpmCenterService {

    private static final Logger LOGGER = LoggerFactory.getLogger(BpmCenterServiceImpl.class);

    @Autowired
    RestClient restClient;

    @Autowired
    AepProperties aepProperties;

    @Autowired
    ICudWinService cudWinService;

    @Autowired
    private MockClient mockClient;

//    @Autowired
//    ICudWinApplication cudWinApplication;

    @Autowired
    CurrentUser currentUser;

    @Autowired
    RequestConditionVO requestConditionVO;

    @Autowired
    IEmailCenterService iEmailCenterService;

    @Value("${cud.psc.appcode:}")
    private String appCode;

    @Value("${aep.appcenter.appId:}")
    private String appId;

    //访问成功状态编码200
    private static final String CODE = "200";

    private String devMode;

    @Value("${spring.profiles.usemock}")
    private void setDevMode(String dm) {
        devMode = dm;
    }

    /**********************************
     * 用途说明: 获取一个流程的初始节点
     * 参数说明 procId
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult getStartAct(String procId) throws Exception {
        if("local".equals(devMode)) {
//            String json = "{\n" +
//                    "    \"responseId\": \"1\",\n" +
//                    "    \"code\": \"200\",\n" +
//                    "    \"msg\": \"成功 \",\n" +
//                    "    \"data\": {\n" +
//                    "        \"task_act_type\": 1,\n" +
//                    "        \"is_merge_task\": 0,\n" +
//                    "        \"act_name\": \"010_填写信息填写信息\",\n" +
//                    "        \"act_uuid\": \"96b77319d53d1732df154a66f888f57c\",\n" +
//                    "        \"act_metadata\": \"010\",\n" +
//                    "        \"task_process_rule\": 1,\n" +
//                    "        \"act_id\": 11114,\n" +
//                    "        \"re_sign_type\": \"0\",\n" +
//                    "        \"proc_id\": 1116\n" +
//                    "    }\n" +
//                    "}\n";
//            return JacksonUtil.readValue(json,ApiResult.class);
            List list = new ArrayList();
            list.add(procId);
            ApiResult invoke = mockClient.invoke("bpmCenterServiceImpl", "getStartAct", list, ApiResult.class,String.class);
            return invoke;

        }
        String realServiceUrl = Constants.BPMCENTER_URL + "/getAct";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;

        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);
        //拼接url
        url = url+"?proc_id="+procId;
        //调用远程接口
        result = restClient.postCgnVoForRest(url,header,null);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 获取流程实例所在节点的下一节点
     * 参数说明 procId
     * 参数说明 actMetadata
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult getNextNode(String procId, String actMetadata) throws Exception {
        String realServiceUrl = Constants.BPMCENTER_URL + "/getNextNode";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;

        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);
        //拼接url
        url = url+"?proc_id="+procId+"&act_metadata="+actMetadata;
        //调用远程接口
        result = restClient.postCgnVoForRest(url,header,null);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 获取流程当前处理人
     * 参数说明 paramsMap
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult queryApprovePerson(Map paramsMap) throws Exception {
        String actId = paramsMap.get("actId").toString();
        String procId = paramsMap.get("procId").toString();
        String procInstId = paramsMap.get("procInstId").toString();
        String node = paramsMap.get("node").toString();

        String realServiceUrl = Constants.BPMCENTER_URL + "/queryApprovePerson";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;

        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);
        String userId = CurrentUser.getUser();
        //拼接url  这里的staffNo 应该是域账号
        StringBuilder urlStringBuilder = new StringBuilder();
        urlStringBuilder.append(url).append("?act_id=").append(actId).append("&procInstId=").
                append(procInstId).append("&proc_id=").append(procId).append("&node=").append(node).
                append("&staffNo=").append(userId);
        url = urlStringBuilder.toString();
        //调用远程接口
        result = restClient.postCgnVoForRest(url,header,null);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 获取流程下一节点处理人
     * 参数说明 procId
     * 参数说明 node
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult getApprovePerson(String procId, String node) throws Exception {
        String realServiceUrl = Constants.BPMCENTER_URL + "/getApprovePerson";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;

        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);
        String userId = CurrentUser.getUser();
        //拼接url  这里的staffNo 应该是域账号
        url = url+"?proc_id="+procId+"&node="+node+"&staffNo="+userId;
        result = restClient.postCgnVoForRest(url,header,null);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 获取下一步点处理人
     * 参数说明 paramsMap
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult getNextApprovePerson(Map paramsMap) throws Exception {
        String actId = paramsMap.get("actId").toString();
        String procId = paramsMap.get("procId").toString();
        String procInstId = paramsMap.get("procInstId").toString();
        String node = paramsMap.get("node").toString();

        String realServiceUrl = Constants.BPMCENTER_URL + "/getNextApprovePerson";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;

        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);
        String userId = CurrentUser.getUser();
        //拼接url  这里的staffNo 应该是域账号
        StringBuilder urlStringBuilder = new StringBuilder();
        urlStringBuilder.append(url).append("?act_id=").append(actId).append("&procInstId=").
                append(procInstId).append("&proc_id=").append(procId).append("&node=").append(node).
                append("&staffNo=").append(userId);
        url = urlStringBuilder.toString();

        if("local".equals(devMode)) {
//            String json = "{\n" +
//                    "    \"responseId\": \"1\",\n" +
//                    "    \"code\": \"200\",\n" +
//                    "    \"msg\": \"成功 \",\n" +
//                    "    \"data\": {\n" +
//                    "        \"030\": [{\n" +
//                    "                \"item_principal_desc\": \"王保齐 \",\n" +
//                    "                \"item_principal\": \"P620311\"\n" +
//                    "            }\n" +
//                    "        ],\n" +
//                    "        \"020\": [{\n" +
//                    "                \"item_principal_desc\": \"何拥军 \",\n" +
//                    "                \"item_principal\": \"PXMWHEY\"\n" +
//                    "            }\n" +
//                    "        ]\n" +
//                    "    }\n" +
//                    "}\n";
//            return JacksonUtil.readValue(json,ApiResult.class);
            List list = new ArrayList();
            list.add(paramsMap);
            ApiResult invoke = mockClient.invoke("bpmCenterServiceImpl", "getNextApprovePerson", list, ApiResult.class,Map.class);
            return invoke;
        }
        LOGGER.info("url：{}",url);
        LOGGER.info("header：{}",JacksonUtil.writeValueAsString(header));
        //调用远程接口
        result = restClient.postCgnVoForRest(url,header,null);
        LOGGER.info("result:{}",JacksonUtil.writeValueAsString(result));
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 获取流程实例所在节点的退回节点
     * 参数说明 procId
     * 参数说明 actMetadata
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult getBackNode(String procId, String actMetadata) throws Exception {
        String realServiceUrl = Constants.BPMCENTER_URL + "/getBackNode";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;

        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);
        //拼接url
        url = url+"?proc_id="+procId+"&act_metadata="+actMetadata;

        if("local".equals(devMode)) {
//            String json = "{\n" +
//                    "    \"responseId\": \"1\",\n" +
//                    "    \"code\": \"200\",\n" +
//                    "    \"msg\": \"成功 \",\n" +
//                    "    \"data\": [{\n" +
//                    "            \"current_act_name\": \"030_确认信息 \",\n" +
//                    "            \"__row_number__\": 1,\n" +
//                    "            \"next_act_metadata\": \"020\",\n" +
//                    "            \"back_uuid\": \"asd45606035d44d3a307e20e5c356754\",\n" +
//                    "            \"proc_id\": 1116,\n" +
//                    "            \"next_act_name\": \"020_审批信息审批信息\",\n" +
//                    "            \"current_act_id\": 11113,\n" +
//                    "            \"next_act_id\": 11115,\n" +
//                    "            \"current_act_metadata\": \"030\"\n" +
//                    "        }\n" +
//                    "    ]\n" +
//                    "}\n";
//            return JacksonUtil.readValue(json,ApiResult.class);
            List l = new ArrayList();
            l.add(procId);
            l.add(actMetadata);
            ApiResult invoke = mockClient.invoke("bpmCenterServiceImpl", "getBackNode", l, ApiResult.class, String.class,String.class);
            return invoke;
        }
        //调用远程接口
        result = restClient.postCgnVoForRest(url,header,null);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 发起一个流程  自动给下一步处理人发邮件
     * 参数说明 map
     * 返回值说明:
     ***********************************/
    @Override
    public  ApiResult startProcess(Map map) throws Exception{
        if("local".equals(devMode)) {
            List list = new ArrayList();
            list.add(map);
            ApiResult invoke = mockClient.invoke("bpmCenterServiceImpl", "startProcess", list, ApiResult.class,Map.class);
            if(!CODE.equals(invoke.getCode())){
                throw new Exception(MessageUtils.message("cud.bpmcenter.error",invoke.getMsg()));
            }
//            ApiResult invoke = ApiResult.success();
            return invoke;
        }
        String nextDealAct = ""; //下一环节
        String nextDealMan = ""; // 下一处理人
        String nextDealManName = "";

//        JSONObject winObj = (JSONObject) map.get("win");
        //下一处理环节  020
        nextDealAct = map.get("next_deal_act").toString();
        //下一环节处理人
        //数组形式   [pxmwrya]阮洋
        JSONArray arrayUser = (JSONArray) map.get("next_deal_name");
        StringBuilder sb1 = new StringBuilder();
        StringBuilder sb2 = new StringBuilder();
        //拼接格式为 sb1: pxmwrya.pxmwxxx    sb2: 阮洋,xxx
        arrayUser.forEach(obj ->{
            String[] userArray = obj.toString().split("]");
            sb1.append(userArray[0].replace('[',' ').trim()+",");
            sb2.append(userArray[1]+",");
        });
        nextDealMan = sb1.substring(0,sb1.lastIndexOf(","));
        nextDealManName = sb2.substring(0,sb2.lastIndexOf(","));

        String realServiceUrl = Constants.BPMCENTER_URL + "/startprocesstorf";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;

        CgnRequestHeader header = null;
        ApiResult result = null;

        header = CgnHeader.getHeader(realServiceUrl,aepProperties);
        //传递参数
        HashMap paramsMap = new HashMap();
        paramsMap.put("account",nextDealMan);
        paramsMap.put("activityName",map.get("act_name").toString());
        paramsMap.put("appTaskID","01");
        paramsMap.put("appTaskTitle","Test");
        paramsMap.put("callbackClassName","");
        paramsMap.put("deptID","");
        paramsMap.put("folio",map.get("folio"));
        paramsMap.put("formNo",map.get("appFormId").toString());
        paramsMap.put("lastDueTime",transDate(new Date()));
        paramsMap.put("mergeTask",map.get("mergeTask").toString());
        paramsMap.put("procInstID","0");
        paramsMap.put("procSetID",map.get("procSetId").toString());
        paramsMap.put("processFullName",map.get("fullName").toString());
        paramsMap.put("processName",map.get("procChName").toString());
        paramsMap.put("processStartTime",transDate(new Date()));
        paramsMap.put("requestConditionVO",requestConditionVO);
        paramsMap.put("senderUserAccent",CurrentUser.getUser());
        paramsMap.put("slotCount",map.get("slotCount").toString());
        paramsMap.put("sourceActMetaData","Start");
        paramsMap.put("startDept","");
        paramsMap.put("startTime",transDate(new Date()));
        paramsMap.put("startUser",CurrentUser.getUser());
        paramsMap.put("startUserCN",CurrentUser.getUserRealName());
        paramsMap.put("targetActMetaData",nextDealAct);
        paramsMap.put("userChsName",nextDealManName);

        StartProcInfo procInfo = new StartProcInfo();
        procInfo.setActivityID("010");//流程环节编号
        procInfo.setActivityName(map.get("act_name").toString());
        procInfo.setCallbackClassName("");
        procInfo.setFolio((String) map.get("folio"));
        procInfo.setFormNo(map.get("appFormId").toString());
        procInfo.setProcSetID(map.get("procSetId").toString());
        procInfo.setProcessFullName(map.get("fullName").toString());
        procInfo.setProcessName(map.get("procChName").toString());
        procInfo.setProcessStartTime(transDate(new Date()));
        procInfo.setStartDept("");
        procInfo.setStartUser(CurrentUser.getUser());
        procInfo.setStartUserCN(CurrentUser.getUserRealName());
        RouteInfo routeInfo = new RouteInfo();
        routeInfo.setIsRouteNotify("false");
        routeInfo.setLineRuleIsFirst("false");
        routeInfo.setProcInstID("0");
        Route route = new Route();
        route.setCurrentStep("0");
        route.setGuidCode("");
        route.setImpersonateUser(CurrentUser.getUser());
        route.setIsActNotify("false");
        route.setSnGroup("");
        route.setSourceActMetaData("Start");
        Step step = new Step();
        step.setActApproveGuid("");
        step.setMergeTask(map.get("mergeTask").toString());
        step.setSlotCount(map.get("slotCount").toString());
        step.setSlotGuid("");
        route.setTargetActMetaData(nextDealAct);
        //多个下一步处理人
        String[] dealerId = sb1.toString().split(",");
        String[] dealerName = sb2.toString().split(",");
        User[] userArray =  new User[dealerId.length];
        User user = new User();
        //拼接需要传递的参数
        for (int i = 0; i < dealerId.length; i++) {
            user.setAccount(dealerId[i]);
            user.setAppTaskID("01");
            user.setAppTaskTitle("test");
            user.setDeptID("");
            user.setIsHidden("false");
            user.setIsMobile("false");
            user.setIsRenew("false");
            user.setIsUserNotify("false");
            user.setLastDueTime(transDate(new Date()));
            user.setOldActInstDest("0");
            user.setOperationType("1");
            user.setSenderUserAccent(CurrentUser.getUser());
            user.setSenderUserDeptID("");
            user.setSnGroup("");
            user.setStartTime(transDate(new Date()));
            user.setUserChsName(dealerName[i]);
            userArray[i] = user;
            user = new User();
        }
        step.setUsers(userArray);
        route.setSteps(new Step[]{step});
        routeInfo.setRoutes(new Route[]{route});
        procInfo.setRouteInfo(routeInfo);
        paramsMap.put("startProcInfo",procInfo);



        LOGGER.info("startProcess paramsMap--{}" , new JSONObject().toJSONString(paramsMap));
        LOGGER.info("startProcess header--{}" , header);
        //调用远程接口
        result = restClient.postCgnVoForRest(url, header, paramsMap);
        LOGGER.info("startProcess result--{}" , result);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }else{
            //发起流程成功，调用发送邮件服务
            UserInfo loginUserInfo = currentUser.getCurrentUserDetail();
            SendEmails emails = iEmailCenterService.buildSendEmails(CurrentUser.getUser(),
                    null,"SCP调试一体化工作平台待办任务提醒<br/>邮件内容:<br/>您好：SCP调试一体化工作平台有待办任务需要处理:"+map.get("procChName").toString() +
                            "<br/>访问地址：https://scp.cgnpc.com.cn/#/need_deal_task"+"<br/>此邮件为自动发送，无需回复<br/>"+
                            loginUserInfo.getUserDept()+":"+loginUserInfo.getDeptCodePath()+"("+loginUserInfo.getUserName()+")","",
                    sb1.substring(0,sb1.lastIndexOf(",")).split(","),map.get("procChName").toString());

            result = iEmailCenterService.sendEmail(emails);
        }
        return result;
    }

    /**********************************
     * 用途说明: 通过流程集全名获取流程集信息 主要是得到当前正在使用的版本以及
     * 参数说明 fullName
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult getProcSetByFullName(String fullName) throws Exception{
        String realServiceUrl = Constants.BPMCENTER_URL + "/GetWfConfigProcSet";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;
        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);

        WFConfigQueryVO wfConfigQueryVO = new WFConfigQueryVO();
        wfConfigQueryVO.setAppCode(appCode);
        wfConfigQueryVO.setFullName(fullName);
        wfConfigQueryVO.setRequestConditionVO(requestConditionVO);
        List<String> list = new ArrayList<>();
        list.add("");
        wfConfigQueryVO.setProcVerIDList(list);

        //调用远程接口
        result = restClient.postCgnVoForRest(url, header, wfConfigQueryVO);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 获取待办列表
     * 参数说明 params
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult getWorkListItems(String params) throws Exception {

        if("local".equals(devMode)) {
//            String json = "{\n" +
//                    "    \"responseId\": \"1\",\n" +
//                    "    \"code\": \"200\",\n" +
//                    "    \"msg\": \"成功 \",\n" +
//                    "    \"data\": {\n" +
//                    "        \"page\": {\n" +
//                    "            \"pageSize\": 1,\n" +
//                    "            \"totalPage\": 29,\n" +
//                    "            \"startPage\": 1,\n" +
//                    "            \"totalCount\": 29\n" +
//                    "        },\n" +
//                    "        \"resultData\": [{\n" +
//                    "                \"appCode\": null,\n" +
//                    "                \"activityID\": \"76778\",\n" +
//                    "                \"workListItemType\": \"1\",\n" +
//                    "                \"sn\": \"376097\",\n" +
//                    "                \"folio\": \"关于张三获奖的流程关于张三获奖的流程\",\n" +
//                    "                \"activityName\": \"030_确认信息确认信息\",\n" +
//                    "                \"processStartTime\": \"2019/11/29 10:00:36\",\n" +
//                    "                \"startUser\": \"PXMWRYA\",\n" +
//                    "                \"startUserCN\": \"PXMWRYA阮洋阮洋\",\n" +
//                    "                \"hasRead\": false,\n" +
//                    "                \"procInstID\": \"80554\",\n" +
//                    "                \"processFullName\": \"BMWS\\\\TestProcess\",\n" +
//                    "                \"processName\": \"兑奖流程兑奖流程\",\n" +
//                    "                \"deptID\": \"\",\n" +
//                    "                \"operationType\": 1,\n" +
//                    "                \"appTaskID\": null,\n" +
//                    "                \"appTaskTitle\": null,\n" +
//                    "                \"lastDueTime\": \"0001-01-01 00:00:00\",\n" +
//                    "                \"procGuid\": \"1ea33d7d1f704efbbb1a80688010e534\",\n" +
//                    "                \"procID\": \"5810\",\n" +
//                    "                \"actionerAccount\": null,\n" +
//                    "                \"actionerChsName\": null,\n" +
//                    "                \"actionerDeptID\": null,\n" +
//                    "                \"delegateAccount\": null,\n" +
//                    "                \"delegateChsName\": null,\n" +
//                    "                \"dflist\": [{\n" +
//                    "                        \"key\": \"Field1\",\n" +
//                    "                        \"value\": \" \"\n" +
//                    "                    }, {\n" +
//                    "                        \"key\": \"Field2\",\n" +
//                    "                        \"value\": \" \"\n" +
//                    "                    }, {\n" +
//                    "                        \"key\": \"Field3\",\n" +
//                    "                        \"value\": \" \"\n" +
//                    "                    }, {\n" +
//                    "                        \"key\": \"Field4\",\n" +
//                    "                        \"value\": \" \"\n" +
//                    "                    }, {\n" +
//                    "                        \"key\": \"Field5\",\n" +
//                    "                        \"value\": \" \"\n" +
//                    "                    }, {\n" +
//                    "                        \"key\": \"Field6\",\n" +
//                    "                        \"value\": \" \"\n" +
//                    "                    }\n" +
//                    "                ],\n" +
//                    "                \"formInstID\": \"e735699d0ebd4af18a35c2c0e96f4b4a\",\n" +
//                    "                \"isDelegated\": false,\n" +
//                    "                \"isProcessing\": false,\n" +
//                    "                \"preActivitySender\": \"pxmwzyp\",\n" +
//                    "                \"preActivitySenderName\": \"张膺鹏张膺鹏\",\n" +
//                    "                \"preActName\": \"020_审批信息审批信息\",\n" +
//                    "                \"taskFlag\": \"1\",\n" +
//                    "                \"taskStartTime\": \"2019/11/29 10:03:33\",\n" +
//                    "                \"taskType\": null,\n" +
//                    "                \"priority\": \"-1\"\n" +
//                    "            }\n" +
//                    "        ]\n" +
//                    "    }\n" +
//                    "}\n";
//            return JacksonUtil.readValue(json,ApiResult.class);

            List list = new ArrayList();
            list.add(params);
            ApiResult invoke = mockClient.invoke("bpmCenterServiceImpl", "getWorkListItems", list, ApiResult.class,String.class);
            return invoke;
        }

        Map paramsMap = JSONObject.parseObject(params);
        String pageIndex = paramsMap.get("pageIndex").toString();
        String pageSize = paramsMap.get("pageSize").toString();

        String realServiceUrl = Constants.BPMCENTER_URL + "/getWorkListItemsSecond";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;

        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);
        //传递参数
        GetWorkListItemsSecondVO toDoTaskQueryVO = new GetWorkListItemsSecondVO();
        toDoTaskQueryVO.setRequestConditionVO(requestConditionVO);
        BpmToDoTaskQuery toDoTaskQuery = new BpmToDoTaskQuery();
        toDoTaskQueryVO.setToDoTaskQuery(toDoTaskQuery);
        toDoTaskQuery.setApp(appCode);

        //设置查询条件  任务描述 发起人 发起时间
        List<BpmToDoTaskFilter> filterList = new ArrayList<>();
        if(!StringUtils.isEmpty(paramsMap.get("taskDesc"))){
            BpmToDoTaskFilter filter = new BpmToDoTaskFilter();
            filter.setField(ToDoTaskField.Folio);
            filter.setValue("%"+paramsMap.get("taskDesc").toString()+"%");
            filter.setLogical(QueryLogical.Empty);
            filter.setOperatoer(QueryOperator.Like);
            filterList.add(filter);
        }
        if(!StringUtils.isEmpty(paramsMap.get("launcher"))){
            BpmToDoTaskFilter filter = new BpmToDoTaskFilter();
            filter.setField(ToDoTaskField.StartUserCN);
            filter.setValue("%"+paramsMap.get("launcher").toString()+"%");
            filter.setLogical(filterList.size() == 0 ? QueryLogical.Empty : QueryLogical.And);
            filter.setOperatoer(QueryOperator.Like);
            filterList.add(filter);
        }
        if(!StringUtils.isEmpty(paramsMap.get("launchTime"))){
            JSONArray timeArr = (JSONArray) paramsMap.get("launchTime");
            if(timeArr.size() >= 2){
                BpmToDoTaskFilter filter1 = new BpmToDoTaskFilter();
                BpmToDoTaskFilter filter2 = new BpmToDoTaskFilter();
                filter1.setField(ToDoTaskField.ProcessStartTime);
                filter1.setValue(timeArr.get(0).toString());
                filter1.setLogical(filterList.size() == 0 ? QueryLogical.Empty : QueryLogical.And);
                filter1.setOperatoer(QueryOperator.Greater);
                filterList.add(filter1);

                filter2.setField(ToDoTaskField.ProcessStartTime);
                filter2.setValue(timeArr.get(1).toString());
                filter2.setLogical(QueryLogical.And);
                filter2.setOperatoer(QueryOperator.LessOrEqual);
                filterList.add(filter2);
            }
        }

        if(filterList.size() > 0){
            toDoTaskQuery.setConditions(filterList);//查询条件
        }else{
            toDoTaskQuery.setConditions(new ArrayList<>());//查询条件
        }

        toDoTaskQuery.setWorkListItemType(1);
        //翻页参数
        QueryPaging paging = new QueryPaging();
        paging.setStartPage(Integer.parseInt(pageIndex));
        paging.setPageSize(Integer.parseInt(pageSize));
        toDoTaskQuery.setPageSetting(paging);
        toDoTaskQuery.setImpersonateUser(CurrentUser.getUser());
        //排序参数
        toDoTaskQuery.setOrderBys(Arrays.asList(ToDoTaskField.ProcessStartTime));
        toDoTaskQuery.setDirection(QueryDirection.DESC);//默认排序
        if(!StringUtils.isEmpty(paramsMap.get("order"))){
            if ("1".equals(paramsMap.get("order"))){
                toDoTaskQuery.setDirection(QueryDirection.DESC);
            }else{
                toDoTaskQuery.setDirection(QueryDirection.ASC);
            }
        }
        LOGGER.info("url:{}", url);
        LOGGER.info("header: {}",header);
        LOGGER.info("toDoTaskQueryVO: {}",toDoTaskQueryVO);
        LOGGER.info("header-json: {}",JacksonUtil.writeValueAsString(header));
        LOGGER.info("toDoTaskQueryVO-json: {}",JacksonUtil.writeValueAsString(toDoTaskQueryVO));


        //调用远程接口
        result = restClient.postCgnVoForRest(url, header, toDoTaskQueryVO);
        LOGGER.info("getWorkListItems result:{}",result.toString());

        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    public ApiResult getWorkListItemsSecond(String params) throws Exception{

        return null;
    }

    /**********************************
     * 用途说明: 获取已办列表
     * 参数说明 map
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult getDoneTaskList(String params) throws Exception {
        Map map = JSONObject.parseObject(params);
        String realServiceUrl = Constants.BPMCENTER_URL + "/getWorkListItemLogs";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;

        String pageIndex = map.get("pageIndex").toString();
        String pageSize = map.get("pageSize").toString();
        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);
        //传递参数
        DoneTaskQueryVO doneTaskQueryVO = new DoneTaskQueryVO();
        doneTaskQueryVO.setRequestConditionVO(requestConditionVO);
        BpmDoneTaskQuery doneTaskQuery = new BpmDoneTaskQuery();
        doneTaskQuery.setApp(appCode);
        /* 查询条件
         * 根据不同条件做调整
         * (cuddemo processName-流程名  taskDes-任务描述  launchTime-发起时间)
         */
        List<BpmDoneTaskFilter> filterList = new ArrayList<>();
        if(!StringUtils.isEmpty(map.get("processName"))){
            BpmDoneTaskFilter filter = new BpmDoneTaskFilter();
            filter.setField(DoneTaskField.ProcessName);
            filter.setLogical(QueryLogical.Empty);
            filter.setOperatoer(QueryOperator.Like);
            filter.setValue("%"+map.get("processName").toString()+"%");

            filterList.add(filter);
        }
        if(!StringUtils.isEmpty(map.get("taskDes"))){
            BpmDoneTaskFilter filter = new BpmDoneTaskFilter();
            filter.setField(DoneTaskField.Folio);
            filter.setLogical(filterList.size() == 0?QueryLogical.Empty:QueryLogical.And);
            filter.setOperatoer(QueryOperator.Like);
            filter.setValue("%"+map.get("taskDes").toString()+"%");
            filterList.add(filter);
        }
        if(!StringUtils.isEmpty(map.get("launchTime"))){
            JSONArray timeArr = (JSONArray) map.get("launchTime");
            if(timeArr.size() >= 2){
                BpmDoneTaskFilter filter1 = new BpmDoneTaskFilter();
                BpmDoneTaskFilter filter2 = new BpmDoneTaskFilter();
                filter1.setField(DoneTaskField.StartTime);
                filter1.setValue(timeArr.get(0).toString());
                filter1.setLogical(filterList.size() == 0 ? QueryLogical.Empty:QueryLogical.And);
                filter1.setOperatoer(QueryOperator.Greater);
                filterList.add(filter1);
                filter2.setField(DoneTaskField.StartTime);
                filter2.setValue(timeArr.get(1).toString());
                filter2.setLogical(QueryLogical.And);
                filter2.setOperatoer(QueryOperator.LessOrEqual);
                filterList.add(filter2);
            }
        }
        doneTaskQuery.setConditions(filterList);//查询条件

        doneTaskQuery.setDirection(QueryDirection.DESC);
        doneTaskQuery.setOrderBys(Arrays.asList(DoneTaskField.StartTime));
        //翻页参数
        QueryPaging paging = new QueryPaging();
        paging.setStartPage(Integer.parseInt(pageIndex));
        paging.setPageSize(Integer.parseInt(pageSize));
        doneTaskQuery.setPageSetting(paging);

        doneTaskQuery.setSqlWhereData("");
        doneTaskQuery.setImpersonateUser(CurrentUser.getUser());

        doneTaskQueryVO.setDoneTaskQuery(doneTaskQuery);
        LOGGER.info("header: {}",header);
        LOGGER.info("toDoTaskQueryVO: {}",doneTaskQueryVO);
        LOGGER.info("header-json: {}",JacksonUtil.writeValueAsString(header));
        LOGGER.info("toDoTaskQueryVO-json: {}",JacksonUtil.writeValueAsString(doneTaskQueryVO));
        if("local".equals(devMode)) {
//            String json = "{\n" +
//                    "  \"responseId\": \"1\",\n" +
//                    "  \"code\": \"200\",\n" +
//                    "  \"msg\": \"成功\",\n" +
//                    "  \"data\": {\n" +
//                    "    \"resultData\": [\n" +
//                    "      {\n" +
//                    "        \"DFList\": [\n" +
//                    "          {\n" +
//                    "            \"value\": \" \",\n" +
//                    "            \"key\": \"Field1\"\n" +
//                    "          },\n" +
//                    "          {\n" +
//                    "            \"value\": \" \",\n" +
//                    "            \"key\": \"Field2\"\n" +
//                    "          },\n" +
//                    "          {\n" +
//                    "            \"value\": \" \",\n" +
//                    "            \"key\": \"Field3\"\n" +
//                    "          },\n" +
//                    "          {\n" +
//                    "            \"value\": \" \",\n" +
//                    "            \"key\": \"Field4\"\n" +
//                    "          },\n" +
//                    "          {\n" +
//                    "            \"value\": \" \",\n" +
//                    "            \"key\": \"Field5\"\n" +
//                    "          },\n" +
//                    "          {\n" +
//                    "            \"value\": \" \",\n" +
//                    "            \"key\": \"Field6\"\n" +
//                    "          }\n" +
//                    "        ],\n" +
//                    "        \"startDept\": \"\",\n" +
//                    "        \"actMetaData\": \"010\",\n" +
//                    "        \"procInstID\": \"80834\",\n" +
//                    "        \"actName\": \"010_填写信息\",\n" +
//                    "        \"processName\": \"兑奖流程\",\n" +
//                    "        \"startTime\": \"2019/12/10 11:43:32\",\n" +
//                    "        \"startUser\": \"pxmwrya\",\n" +
//                    "        \"processFullName\": \"BMWS\\\\TestProcess\",\n" +
//                    "        \"fromNO\": \"ac995bdfb3984126b70440b1b7316f15\",\n" +
//                    "        \"actID\": \"76779\",\n" +
//                    "        \"appTaskTitle\": \"\",\n" +
//                    "        \"procID\": \"5810\",\n" +
//                    "        \"approveWorkID\": \"0\",\n" +
//                    "        \"startCNUser\": \"阮洋\",\n" +
//                    "        \"priority\": \"-1\",\n" +
//                    "        \"appTaskID\": \"\",\n" +
//                    "        \"lastDueTime\": {\n" +
//                    "          \"date\": 1,\n" +
//                    "          \"hours\": 0,\n" +
//                    "          \"seconds\": 0,\n" +
//                    "          \"month\": 0,\n" +
//                    "          \"timezoneOffset\": -480,\n" +
//                    "          \"year\": -1899,\n" +
//                    "          \"minutes\": 0,\n" +
//                    "          \"time\": -62135798400000,\n" +
//                    "          \"day\": 6\n" +
//                    "        },\n" +
//                    "        \"procGuid\": \"da6c4fbcd3304122bdc7c59b5b28af1b\",\n" +
//                    "        \"approveDeptID\": \"\",\n" +
//                    "        \"folio\": \"关于565656获奖的流程\",\n" +
//                    "        \"finishDate\": \"2019/12/10 11:43:31\",\n" +
//                    "        \"endTime\": \"2019/12/10 11:43:32\",\n" +
//                    "        \"procSetID\": \"463\",\n" +
//                    "        \"status\": \"运行中\"\n" +
//                    "      }\n" +
//                    "    ],\n" +
//                    "    \"page\": {\n" +
//                    "      \"startPage\": 1,\n" +
//                    "      \"totalPage\": 0,\n" +
//                    "      \"pageSize\": 1,\n" +
//                    "      \"totalCount\": 112\n" +
//                    "    }\n" +
//                    "  }\n" +
//                    "}";
//            return JacksonUtil.readValue(json,ApiResult.class);
            List list = new ArrayList();
            list.add(params);
            ApiResult invoke = mockClient.invoke("bpmCenterServiceImpl", "getDoneTaskList", list, ApiResult.class,String.class);
            return invoke;
        }

        //调用远程接口
        result = restClient.postCgnVoForRest(url, header, doneTaskQueryVO);
        LOGGER.info("getDoneTaskList result:{}",result.toString());

        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 获取办文跟踪
     * 参数说明 map
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult getWorkListItemTrace(Map map) throws Exception {
        String procInstId = map.get("procInsId").toString();
        String pageIndex = map.get("pageIndex").toString();
        String pageSize = map.get("pageSize").toString();

        String realServiceUrl = Constants.BPMCENTER_URL + "/GetWorkListItemTrace";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;
        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);
        //条件参数
        ProcessLogQueryVO processLogQueryVO = new ProcessLogQueryVO();
        List<ProcessLogField> list1 = new ArrayList<>();
        List<BpmProcessLogFilter> list2 = new ArrayList<>();
        list1.add(ProcessLogField.StartDate);
        processLogQueryVO.setOrderBys(list1);
        processLogQueryVO.setDirection(QueryDirection.ASC);
        processLogQueryVO.setConditions(list2);
        processLogQueryVO.setHasRead(true);
        processLogQueryVO.setProcInstID(procInstId);

        QueryPaging PageSetting = new QueryPaging();
        PageSetting.setStartPage(Integer.parseInt(pageIndex));
        PageSetting.setPageSize(Integer.parseInt(pageSize));
        PageSetting.setTotalCount(0);
        PageSetting.setTotalPage(0);
        processLogQueryVO.setPageSetting(PageSetting);

        processLogQueryVO.setRequestConditionVO(requestConditionVO);

        if("local".equals(devMode)) {
//            String json = "{\n" +
//                    "    \"responseId\": \"1\",\n" +
//                    "    \"code\": \"200\",\n" +
//                    "    \"msg\": \"成功\",\n" +
//                    "    \"data\": {\n" +
//                    "        \"Paging\": {\n" +
//                    "            \"pageSize\": 10,\n" +
//                    "            \"totalPage\": 0,\n" +
//                    "            \"startPage\": 1,\n" +
//                    "            \"totalCount\": 5\n" +
//                    "        },\n" +
//                    "        \"ProcessTraces\": [{\n" +
//                    "                \"nextActInfo\": [],\n" +
//                    "                \"processLogDTO\": {\n" +
//                    "                    \"sn\": \"362571\",\n" +
//                    "                    \"hasRead\": 1,\n" +
//                    "                    \"procInstID\": 77308,\n" +
//                    "                    \"operationType\": \"1\",\n" +
//                    "                    \"processLogID\": 296578,\n" +
//                    "                    \"action\": 1,\n" +
//                    "                    \"actName\": \"020_审批信息\",\n" +
//                    "                    \"isDelegated\": false,\n" +
//                    "                    \"actID\": 11115,\n" +
//                    "                    \"finished\": \"1\",\n" +
//                    "                    \"delegatedByChsName\": \"\",\n" +
//                    "                    \"delegatedByAccount\": \"\",\n" +
//                    "                    \"actInstDestID\": 362571,\n" +
//                    "                    \"approverDept\": \"\",\n" +
//                    "                    \"finishDate\": \"2019-08-09T11:56:36\",\n" +
//                    "                    \"approverAccount\": \"pxmwrya\",\n" +
//                    "                    \"ccid\": \"362571\",\n" +
//                    "                    \"enabledFlag\": false,\n" +
//                    "                    \"startDate\": \"2019-08-09T11:55:03\",\n" +
//                    "                    \"approverChsName\": \"阮洋\",\n" +
//                    "                    \"comment\": \"同意!\"\n" +
//                    "                }\n" +
//                    "            }\n" +
//                    "        ]\n" +
//                    "    }\n" +
//                    "}\n";
//            return JacksonUtil.readValue(json,ApiResult.class);
            List list = new ArrayList();
            list.add(map);
            ApiResult invoke = mockClient.invoke("bpmCenterServiceImpl", "getWorkListItemTrace", list, ApiResult.class,Map.class);
            return invoke;
        }

        //调用远程接口
        result = restClient.postCgnVoForRest(url, header, processLogQueryVO);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 提交流程
     * 参数说明 map
     * 返回值说明:
     ***********************************/
    @Override
    @Transactional
    public ApiResult submitworklistitem(Map map) throws Exception{
        if("local".equals(devMode)) {
            List list = new ArrayList();
            list.add(map);
            ApiResult invoke = mockClient.invoke("bpmCenterServiceImpl", "submitworklistitem", list, ApiResult.class,Map.class);
            return invoke;
//            return ApiResult.success();
        }
        String sn = map.get("sn").toString();
        String procInstId = map.get("procInstId").toString();
        String dealSuggest = "";
        String copygive = "";//以数组的形式传过来
        String nextDealMan = "";
        String nextDealManName = "";
        String mergeTask = map.get("mergeTask").toString();
        String slotCount = map.get("slotCount").toString();
        String nowAct = map.get("now_deal_act").toString();
        String nextAct = map.get("next_deal_act").toString();
        String actId = map.get("actId").toString();
        String procid = map.get("procId").toString();
        String staffNoBefore = map.get("staffNoBefore").toString();

        //下一步处理人  形式:[p123456]张三
        if(map.get("isEnd").toString().equals("false") ){
            JSONArray staff = (JSONArray) map.get("next_deal_name");
            StringBuilder sb1 = new StringBuilder();
            StringBuilder sb2 = new StringBuilder();
            for (int i = 0; i < staff.size(); i++) {
                String[] userArray = staff.get(i).toString().split("]");
                sb1.append(userArray[0].replace('[',' ').trim()+",");
                sb2.append(userArray[1]+",");
            }
            nextDealMan = sb1.substring(0,sb1.lastIndexOf(","));
            nextDealManName = sb2.substring(0,sb2.lastIndexOf(","));
        }
        //抄送
        JSONArray copySendArray = null;
        if(!StringUtils.isEmpty(map.get("copygive"))){
            copySendArray = (JSONArray) map.get("copygive");
            copygive = org.apache.commons.lang.StringUtils.join(copySendArray,',');
        }
        //处理意见
        if(!StringUtils.isEmpty(map.get("deal_suggest"))){
            dealSuggest = map.get("deal_suggest").toString();
        }

        String realServiceUrl = Constants.BPMCENTER_URL + "/submitworklistitem";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;
        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);
        //请求参数
        HashMap paramsMap = new HashMap();
        paramsMap.put("act_id",actId);
        paramsMap.put("proc_id",procid);
        paramsMap.put("node",nowAct);
        paramsMap.put("isRouteNotify",false);
        paramsMap.put("lineRuleIsFirst",false);
        paramsMap.put("requestConditionVO",requestConditionVO);
        paramsMap.put("staffNoBefore",staffNoBefore);
        SubmitProcInfo procInfo = new SubmitProcInfo();

        procInfo.setAction("1");
        procInfo.setCallbackClassName("");
        procInfo.setComment(dealSuggest);//处理意见
        procInfo.setCopyType("0");
        procInfo.setIsCopySend("false");
        procInfo.setIsFinishedGroup("false");
        procInfo.setIsImmediacyEnd("false");
        procInfo.setNotifyType("0");
        procInfo.setProcInstID(procInstId);
        procInfo.setSN(sn);
        procInfo.setSubmitUser(CurrentUser.getUser());
        procInfo.setSubmitUserChName(CurrentUser.getUserRealName());
        procInfo.setSuspended("false");//抄送
        procInfo.setUserDept("");

        //测试 copySendUsers  是否为 抄送    好像这个抄送没用
//        procInfo.setCopySendUsers(users.length != 0? users : null);
        procInfo.setCopySendUsers(null);
        RouteInfo routeInfo = new RouteInfo();
        routeInfo.setIsRouteNotify("false");
        routeInfo.setLineRuleIsFirst("false");
        routeInfo.setProcInstID(procInstId);
        Route route = new Route();
        route.setCurrentStep("0");
        route.setGuidCode("");
        route.setImpersonateUser(CurrentUser.getUser());
        route.setIsActNotify("false");
        route.setSnGroup("");
        route.setSourceActMetaData(nowAct);
        route.setTargetActMetaData(nextAct);

        Step step = new Step();
        step.setActApproveGuid("");
        step.setMergeTask(mergeTask);
        step.setSlotCount(slotCount);
        step.setSlotGuid("");
        //多个下一步处理人
        String[] dealerId = nextDealMan.toString().split(",");
        String[] dealerName = nextDealManName.toString().split(",");
        User[] userArray =  new User[dealerId.length];
        User tempUser = new User();
        for (int i = 0; i < dealerId.length; i++) {
            tempUser.setAccount(dealerId[i]);
            tempUser.setAppTaskID("1");
            tempUser.setAppTaskTitle("test");
            tempUser.setDeptID("");
            tempUser.setIsHidden("false");
            tempUser.setIsMobile("false");
            tempUser.setIsRenew("false");
            tempUser.setIsUserNotify("false");
            tempUser.setLastDueTime(transDate(new Date()));
            tempUser.setOldActInstDest("0");
            tempUser.setOperationType("1");
            tempUser.setSenderUserAccent(CurrentUser.getUser());
            tempUser.setSenderUserDeptID("");
            tempUser.setSnGroup("");
            tempUser.setStartTime(transDate(new Date()));
            tempUser.setUserChsName(dealerName[i]);
            userArray[i] = tempUser;
            tempUser = new User();
        }
        step.setUsers(userArray);
        route.setSteps(new Step[]{step});
        routeInfo.setRoutes(new Route[]{route});
        procInfo.setRouteInfo(routeInfo);
        paramsMap.put("submitProcInfo",procInfo);

        //好像还是得先执行 抄送 后提交流程才行 这里试一下
        ArrayList idList = new ArrayList();
        ArrayList nameList = new ArrayList();
        LOGGER.info("submitworklistitem map:{}",JacksonUtil.writeValueAsString(map));


        if(!StringUtils.isEmpty(copygive)){
            HashMap sendMap = new HashMap();
            sendMap.put("dealSuggest",dealSuggest);//处理意见
            sendMap.put("procInstId",procInstId);//流程实例
            sendMap.put("sourceAct",nowAct);//当前节点  020
            sendMap.put("targetAct",nextAct);//下一节点 030
            sendMap.put("sn",sn);
            sendMap.put("slotCount",slotCount);
            sendMap.put("mergeTask",mergeTask);
            JSONArray array = (JSONArray) map.get("copygive");//[pxmwxxx]xxx
            //分别添加id和name 到 列表中
            array.forEach(n -> {
                idList.add(n.toString().substring(1,n.toString().lastIndexOf(']')));
                nameList.add(n.toString().substring(n.toString().lastIndexOf(']')+1));
            });
            //map 保存数组会转换为Map
            sendMap.put("userIds", org.apache.commons.lang.StringUtils.join(idList,","));
            sendMap.put("userNames", org.apache.commons.lang.StringUtils.join(nameList,","));
            ApiResult copySendResult = copySendWorkListItem(sendMap);//调用抄送 提交的copySend好像无效
            //判断抄送接口是否调用成功，成功则执行
            if((copySendResult!= null && CODE.equals(copySendResult.getCode())) || StringUtils.isEmpty(copygive)){
                //调用远程接口
                result = restClient.postCgnVoForRest(url, header, paramsMap);
                if(!CODE.equals(result.getCode())){
                    throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
                }
            }else{
                throw new Exception(copySendResult.getMsg());
            }
        }else{
            //调用远程接口
            result = restClient.postCgnVoForRest(url, header, paramsMap);
            if(!CODE.equals(result.getCode())){
                throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
            }
        }
        //发起流程成功，调用发送邮件服务
        if(map.get("isEnd").toString().equals("false")){
            UserInfo loginUserInfo = currentUser.getCurrentUserDetail();
            String username =loginUserInfo.getUserDept()+":"+loginUserInfo.getDeptCodePath()+"("+loginUserInfo.getUserName()+")";
            SendEmails emails = iEmailCenterService.buildSendEmails(CurrentUser.getUser(),
                    StringUtils.toStringArray(idList), "SCP调试一体化工作平台待办任务提醒<br/>邮件内容:<br/>您好：SCP调试一体化工作平台有待办任务需要处理:"+map.get("procChName").toString() +
                            "<br/>访问地址：https://scp.cgnpc.com.cn/#/need_deal_task"+"<br/>此邮件为自动发送，无需回复<br/>"+
                            loginUserInfo.getUserDept()+":"+loginUserInfo.getDeptCodePath()+"("+loginUserInfo.getUserName()+")","",
                    dealerId,map.get("procChName").toString());
            //调用邮件服务接口
            iEmailCenterService.sendEmail(emails);
        }
        return result;
    }

    /**********************************
     * 用途说明: 获取流程节点信息 (非流程实例)
     * 参数说明 map
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult getWFConfigActivity(Map map) throws Exception {
        String fullName = map.get("fullName").toString();
        String procSetId = null;
        if(!StringUtils.isEmpty(map.get("procSetId")) ){
            procSetId = map.get("procSetId").toString();
        }

        String realServiceUrl = Constants.BPMCENTER_URL + "/GetWFConfigActivity";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;
        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);
        //传递参数
        WFConfigQueryVO wfConfigQueryVO = new WFConfigQueryVO();
        wfConfigQueryVO.setAppCode(appCode);
        wfConfigQueryVO.setFullName(fullName);
        wfConfigQueryVO.setProcVerIDList(Arrays.asList(procSetId));
        wfConfigQueryVO.setRequestConditionVO(requestConditionVO);

        if("local".equals(devMode)) {
//            String json = "{\n" +
//                    "  \"responseId\": \"1\",\n" +
//                    "  \"code\": \"200\",\n" +
//                    "  \"msg\": \"成功\",\n" +
//                    "  \"data\": [\n" +
//                    "    {\n" +
//                    "      \"procID\": 5810,\n" +
//                    "      \"actName\": \"Start\",\n" +
//                    "      \"actSlots\": 0,\n" +
//                    "      \"actType\": 3,\n" +
//                    "      \"actUseTran\": 0,\n" +
//                    "      \"actWorkID\": 0,\n" +
//                    "      \"actDesc\": \"\",\n" +
//                    "      \"actPriority\": 1,\n" +
//                    "      \"actID\": 76777,\n" +
//                    "      \"actMetaData\": \"\",\n" +
//                    "      \"actExpectedDuration\": 0\n" +
//                    "    },\n" +
//                    "    {\n" +
//                    "      \"procID\": 5810,\n" +
//                    "      \"actName\": \"030_确认信息\",\n" +
//                    "      \"actSlots\": 0,\n" +
//                    "      \"actType\": 1,\n" +
//                    "      \"actUseTran\": 0,\n" +
//                    "      \"actWorkID\": 0,\n" +
//                    "      \"actDesc\": \"\",\n" +
//                    "      \"actPriority\": 1,\n" +
//                    "      \"actID\": 76778,\n" +
//                    "      \"actMetaData\": \"030\",\n" +
//                    "      \"actExpectedDuration\": 0\n" +
//                    "    },\n" +
//                    "    {\n" +
//                    "      \"procID\": 5810,\n" +
//                    "      \"actName\": \"010_填写信息\",\n" +
//                    "      \"actSlots\": 0,\n" +
//                    "      \"actType\": 1,\n" +
//                    "      \"actUseTran\": 0,\n" +
//                    "      \"actWorkID\": 0,\n" +
//                    "      \"actDesc\": \"\",\n" +
//                    "      \"actPriority\": 1,\n" +
//                    "      \"actID\": 76779,\n" +
//                    "      \"actMetaData\": \"010\",\n" +
//                    "      \"actExpectedDuration\": 0\n" +
//                    "    },\n" +
//                    "    {\n" +
//                    "      \"procID\": 5810,\n" +
//                    "      \"actName\": \"020_审批信息\",\n" +
//                    "      \"actSlots\": 0,\n" +
//                    "      \"actType\": 1,\n" +
//                    "      \"actUseTran\": 0,\n" +
//                    "      \"actWorkID\": 0,\n" +
//                    "      \"actDesc\": \"\",\n" +
//                    "      \"actPriority\": 1,\n" +
//                    "      \"actID\": 76780,\n" +
//                    "      \"actMetaData\": \"020\",\n" +
//                    "      \"actExpectedDuration\": 0\n" +
//                    "    },\n" +
//                    "    {\n" +
//                    "      \"procID\": 5810,\n" +
//                    "      \"actName\": \"流程结束\",\n" +
//                    "      \"actSlots\": 1,\n" +
//                    "      \"actType\": 3,\n" +
//                    "      \"actUseTran\": 0,\n" +
//                    "      \"actWorkID\": 0,\n" +
//                    "      \"actDesc\": \"\",\n" +
//                    "      \"actPriority\": 1,\n" +
//                    "      \"actID\": 76781,\n" +
//                    "      \"actMetaData\": \"END\",\n" +
//                    "      \"actExpectedDuration\": 0\n" +
//                    "    }\n" +
//                    "  ]\n" +
//                    "}";
//            return JacksonUtil.readValue(json,ApiResult.class);
            List list = new ArrayList();
            list.add(map);
            ApiResult invoke = mockClient.invoke("bpmCenterServiceImpl", "getWFConfigActivity", list, ApiResult.class,Map.class);
            return invoke;

        }

        //调用远程接口
        result = restClient.postCgnVoForRest(url, header, wfConfigQueryVO);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 通过流程全名 和 appcode  获取流程信息 (不是流程实例信息)
     * 参数说明 map
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult getProcessInfo(Map map) throws Exception {
        String procInsId = map.get("procInsId").toString();
        String fullProcName = map.get("fullName").toString();
        String realServiceUrl = Constants.BPMCENTER_URL + "/GetProcessInfo?var="+procInsId;
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;

        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);

        WFConfigQueryVO wfConfigQueryVO = new WFConfigQueryVO();
        wfConfigQueryVO.setAppCode(appCode);
        wfConfigQueryVO.setFullName(fullProcName);
        wfConfigQueryVO.setRequestConditionVO(requestConditionVO);

        //调用远程接口
        result = restClient.postCgnVoForRest(url, header, wfConfigQueryVO);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 获取流程线数据
     * 参数说明 params
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult getWFConfigLine(String params) throws Exception {
        Map map = JSONObject.parseObject(params);
        String procFullName = map.get("fullName").toString();

        String realServiceUrl = Constants.BPMCENTER_URL + "/GetWFConfigLine";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;
        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);

        WFConfigQueryVO wfConfigQueryVO = new WFConfigQueryVO();
        wfConfigQueryVO.setAppCode(appCode);
        wfConfigQueryVO.setFullName(procFullName);
        wfConfigQueryVO.setRequestConditionVO(requestConditionVO);

        //调用远程接口
        result = restClient.postCgnVoForRest(url, header, wfConfigQueryVO);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;

    }

    /**********************************
     * 用途说明: 获取流程版本  (非List 应该是只显示在用版本  ***并给出了开始节点)
     * 参数说明 params
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult getWFConfigProc(String params) throws Exception {
        Map map = JSONObject.parseObject(params);
        String procFullName = map.get("fullName").toString();

        String realServiceUrl = Constants.BPMCENTER_URL + "/GetWFConfigProc";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;
        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);

        WFConfigQueryVO wfConfigQueryVO = new WFConfigQueryVO();
        wfConfigQueryVO.setAppCode(appCode);
        wfConfigQueryVO.setFullName(procFullName);
        wfConfigQueryVO.setRequestConditionVO(requestConditionVO);

        if("local".equals(devMode)) {
            String json = "{\n" +
                    "    \"responseId\": \"1\",\n" +
                    "    \"code\": \"200\",\n" +
                    "    \"msg\": \"成功\",\n" +
                    "    \"data\": [{\n" +
                    "            \"expectedDuration\": 0,\n" +
                    "            \"changeDate\": \"2020-08-18 10:47:16\",\n" +
                    "            \"exportID\": 6681,\n" +
                    "            \"startActID\": 93011,\n" +
                    "            \"ver\": 1,\n" +
                    "            \"metaData\": \"\",\n" +
                    "            \"workID\": 0,\n" +
                    "            \"procSetID\": 1932,\n" +
                    "            \"procID\": 7355,\n" +
                    "            \"priority\": 1\n" +
                    "        }, {\n" +
                    "            \"expectedDuration\": 0,\n" +
                    "            \"changeDate\": \"2020-08-18 10:49:54\",\n" +
                    "            \"exportID\": 6682,\n" +
                    "            \"startActID\": 93038,\n" +
                    "            \"ver\": 2,\n" +
                    "            \"metaData\": \"\",\n" +
                    "            \"workID\": 0,\n" +
                    "            \"procSetID\": 1932,\n" +
                    "            \"procID\": 7360,\n" +
                    "            \"priority\": 1\n" +
                    "        }, {\n" +
                    "            \"expectedDuration\": 0,\n" +
                    "            \"changeDate\": \"2020-08-18 10:52:55\",\n" +
                    "            \"exportID\": 6683,\n" +
                    "            \"startActID\": 93065,\n" +
                    "            \"ver\": 3,\n" +
                    "            \"metaData\": \"\",\n" +
                    "            \"workID\": 0,\n" +
                    "            \"procSetID\": 1932,\n" +
                    "            \"procID\": 7365,\n" +
                    "            \"priority\": 1\n" +
                    "        }, {\n" +
                    "            \"expectedDuration\": 0,\n" +
                    "            \"changeDate\": \"2020-08-18 10:59:39\",\n" +
                    "            \"exportID\": 6684,\n" +
                    "            \"startActID\": 93092,\n" +
                    "            \"ver\": 4,\n" +
                    "            \"metaData\": \"\",\n" +
                    "            \"workID\": 0,\n" +
                    "            \"procSetID\": 1932,\n" +
                    "            \"procID\": 7370,\n" +
                    "            \"priority\": 1\n" +
                    "        }, {\n" +
                    "            \"expectedDuration\": 0,\n" +
                    "            \"changeDate\": \"2020-08-18 11:09:59\",\n" +
                    "            \"exportID\": 6685,\n" +
                    "            \"startActID\": 93119,\n" +
                    "            \"ver\": 5,\n" +
                    "            \"metaData\": \"\",\n" +
                    "            \"workID\": 0,\n" +
                    "            \"procSetID\": 1932,\n" +
                    "            \"procID\": 7375,\n" +
                    "            \"priority\": 1\n" +
                    "        }, {\n" +
                    "            \"expectedDuration\": 0,\n" +
                    "            \"changeDate\": \"2020-08-18 11:44:17\",\n" +
                    "            \"exportID\": 6686,\n" +
                    "            \"startActID\": 93146,\n" +
                    "            \"ver\": 6,\n" +
                    "            \"metaData\": \"\",\n" +
                    "            \"workID\": 0,\n" +
                    "            \"procSetID\": 1932,\n" +
                    "            \"procID\": 7380,\n" +
                    "            \"priority\": 1\n" +
                    "        }\n" +
                    "    ]\n" +
                    "}\n";
            return JacksonUtil.readValue(json,ApiResult.class);
        }

        //调用远程接口
        result = restClient.postCgnVoForRest(url, header, wfConfigQueryVO);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 获取流程最新ProcID  (非List 应该是只显示在用版本  ***并给出了开始节点)
     * 参数说明 params
     * 返回值说明:
     ***********************************/
    @Override
    public Map getWFConfigProcID(String params) throws Exception {
        Map map = JSONObject.parseObject(params);
        String procFullName = map.get("fullName").toString();

        String realServiceUrl = Constants.BPMCENTER_URL + "/GetWFConfigProc";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;
        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);

        WFConfigQueryVO wfConfigQueryVO = new WFConfigQueryVO();
        wfConfigQueryVO.setAppCode(appCode);
        wfConfigQueryVO.setFullName(procFullName);
        wfConfigQueryVO.setRequestConditionVO(requestConditionVO);

        if("local".equals(devMode)) {
//            String json = "{\n" +
//                    "    \"responseId\": \"1\",\n" +
//                    "    \"code\": \"200\",\n" +
//                    "    \"msg\": \"成功\",\n" +
//                    "    \"data\": [{\n" +
//                    "            \"expectedDuration\": 0,\n" +
//                    "            \"changeDate\": \"2020-08-18 10:47:16\",\n" +
//                    "            \"exportID\": 6681,\n" +
//                    "            \"startActID\": 93011,\n" +
//                    "            \"ver\": 1,\n" +
//                    "            \"metaData\": \"\",\n" +
//                    "            \"workID\": 0,\n" +
//                    "            \"procSetID\": 1932,\n" +
//                    "            \"procID\": 7355,\n" +
//                    "            \"priority\": 1\n" +
//                    "        }, {\n" +
//                    "            \"expectedDuration\": 0,\n" +
//                    "            \"changeDate\": \"2020-08-18 10:49:54\",\n" +
//                    "            \"exportID\": 6682,\n" +
//                    "            \"startActID\": 93038,\n" +
//                    "            \"ver\": 2,\n" +
//                    "            \"metaData\": \"\",\n" +
//                    "            \"workID\": 0,\n" +
//                    "            \"procSetID\": 1932,\n" +
//                    "            \"procID\": 7360,\n" +
//                    "            \"priority\": 1\n" +
//                    "        }, {\n" +
//                    "            \"expectedDuration\": 0,\n" +
//                    "            \"changeDate\": \"2020-08-18 10:52:55\",\n" +
//                    "            \"exportID\": 6683,\n" +
//                    "            \"startActID\": 93065,\n" +
//                    "            \"ver\": 3,\n" +
//                    "            \"metaData\": \"\",\n" +
//                    "            \"workID\": 0,\n" +
//                    "            \"procSetID\": 1932,\n" +
//                    "            \"procID\": 7365,\n" +
//                    "            \"priority\": 1\n" +
//                    "        }, {\n" +
//                    "            \"expectedDuration\": 0,\n" +
//                    "            \"changeDate\": \"2020-08-18 10:59:39\",\n" +
//                    "            \"exportID\": 6684,\n" +
//                    "            \"startActID\": 93092,\n" +
//                    "            \"ver\": 4,\n" +
//                    "            \"metaData\": \"\",\n" +
//                    "            \"workID\": 0,\n" +
//                    "            \"procSetID\": 1932,\n" +
//                    "            \"procID\": 7370,\n" +
//                    "            \"priority\": 1\n" +
//                    "        }, {\n" +
//                    "            \"expectedDuration\": 0,\n" +
//                    "            \"changeDate\": \"2020-08-18 11:09:59\",\n" +
//                    "            \"exportID\": 6685,\n" +
//                    "            \"startActID\": 93119,\n" +
//                    "            \"ver\": 5,\n" +
//                    "            \"metaData\": \"\",\n" +
//                    "            \"workID\": 0,\n" +
//                    "            \"procSetID\": 1932,\n" +
//                    "            \"procID\": 7375,\n" +
//                    "            \"priority\": 1\n" +
//                    "        }, {\n" +
//                    "            \"expectedDuration\": 0,\n" +
//                    "            \"changeDate\": \"2020-08-18 11:44:17\",\n" +
//                    "            \"exportID\": 6686,\n" +
//                    "            \"startActID\": 93146,\n" +
//                    "            \"ver\": 6,\n" +
//                    "            \"metaData\": \"\",\n" +
//                    "            \"workID\": 0,\n" +
//                    "            \"procSetID\": 1932,\n" +
//                    "            \"procID\": 7380,\n" +
//                    "            \"priority\": 1\n" +
//                    "        }\n" +
//                    "    ]\n" +
//                    "}\n";
//            return BpmUtil.getProcID(JacksonUtil.readValue(json,ApiResult.class));
            List list = new ArrayList();
            list.add(params);
            Map i = mockClient.invoke("bpmCenterServiceImpl", "getWFConfigProcID", list, Map.class,String.class);
            return i;
        }

        //调用远程接口
        LOGGER.info("url:{}",url);
        LOGGER.info("header:{}",JacksonUtil.writeValueAsString(header));
        LOGGER.info("wfConfigQueryVO:{}",JacksonUtil.writeValueAsString(wfConfigQueryVO));
        result = restClient.postCgnVoForRest(url, header, wfConfigQueryVO);
        LOGGER.info("result:{}",JacksonUtil.writeValueAsString(result));
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return BpmUtil.getProcID(result);
    }

    /**********************************
     * 用途说明: 获取流程集信息
     * 参数说明 map
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult getWFConfigProcSet(Map map) throws Exception {
        //Map map = JSONObject.parseObject(params);
        //这个好像不行 报500 连接服务端出错 500  找到原因 WFC的F 是小写的
        String procFullName = map.get("fullName").toString();

        String realServiceUrl = Constants.BPMCENTER_URL + "/GetWfConfigProcSet";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;
        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);

        WFConfigQueryVO wfConfigQueryVO = new WFConfigQueryVO();
        wfConfigQueryVO.setAppCode(appCode);
        wfConfigQueryVO.setFullName(procFullName);
        wfConfigQueryVO.setRequestConditionVO(requestConditionVO);
        List<String> list = new ArrayList<>();
        list.add("");
        wfConfigQueryVO.setProcVerIDList(list);

        //调用远程接口
        result = restClient.postCgnVoForRest(url, header, wfConfigQueryVO);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;

    }

    /**********************************
     * 用途说明: 请求调用查询流程实例
     * 参数说明 params
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult getProcessInfoList(String params) throws Exception {
        Map map = JSONObject.parseObject(params);
        String pageIndex = map.get("pageIndex").toString();
        String pageSize = map.get("pageSize").toString();

        String realServiceUrl = Constants.BPMCENTER_URL + "/GetProcessInfoList";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;
        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);

        ProcessInstenceQueryVO procInstQueryVo = new ProcessInstenceQueryVO();
        QueryPaging queryPaging = new QueryPaging();
        queryPaging.setStartPage(Integer.parseInt(pageIndex));
        queryPaging.setPageSize(Integer.parseInt(pageSize));
        queryPaging.setTotalCount(0);
        queryPaging.setTotalPage(0);

        procInstQueryVo.setPageSetting(queryPaging);

        List list1 = new ArrayList<>();
        List list2 = new ArrayList<>();

        list1.add(ProcessInstenceField.ProcInstID);
        procInstQueryVo.setOrderBys(list1);
        procInstQueryVo.setConditions(list2);
        procInstQueryVo.setDirection(QueryDirection.ASC);
        procInstQueryVo.setRequestConditionVO(requestConditionVO);

        //调用远程接口
        result = restClient.postCgnVoForRest(url, header, procInstQueryVo);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 返回调用查询流程实例
     * 参数说明 params
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult getBackProcessInfoList(String params) throws Exception {
        Map map = JSONObject.parseObject(params);
        String pageIndex = map.get("pageIndex").toString();
        String pageSize = map.get("pageSize").toString();

        String realServiceUrl = Constants.BPMCENTER_URL + "/BackProcessInfoList";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;
        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);

        ProcessInstenceQueryVO procInstVo = new ProcessInstenceQueryVO();
        QueryPaging queryPaging = new QueryPaging();
        queryPaging.setStartPage(Integer.parseInt(pageIndex));
        queryPaging.setPageSize(Integer.parseInt(pageSize));
        queryPaging.setTotalPage(0);
        queryPaging.setTotalCount(0);
        procInstVo.setPageSetting(queryPaging);

        //调用远程接口
        result = restClient.postCgnVoForRest(url, header, procInstVo);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 作废流程
     * 参数说明 params
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult cancelProc(String params) throws Exception {
        Map map = JSONObject.parseObject(params);
        String sn = map.get("sn").toString();
        String procInsId = map.get("procInsId").toString();

        String realServiceUrl = Constants.BPMCENTER_URL + "/cancelproc";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;
        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);

        CancelProcInfoVO cancelProcInfoVO = new CancelProcInfoVO();
        cancelProcInfoVO.setRequestConditionVO(requestConditionVO);
        cancelProcInfoVO.setComment("");
        cancelProcInfoVO.setEmailTemplateID("");
        cancelProcInfoVO.setKey("");
        cancelProcInfoVO.setMessageTemplateID("");
        cancelProcInfoVO.setNotifyTypes("");
        cancelProcInfoVO.setSubject("");
        cancelProcInfoVO.setValue("");
        cancelProcInfoVO.setImpersonateUser(CurrentUser.getUser());
        cancelProcInfoVO.setImpersonateUserChsName(CurrentUser.getUserRealName());
        cancelProcInfoVO.setProcInstID(procInsId);
        cancelProcInfoVO.setSn(sn);

        //调用远程接口
        result = restClient.postCgnVoForRest(url, header, cancelProcInfoVO);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 回调接口
     * 参数说明 params
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult collBack(String params) throws Exception {
        Map map = JSONObject.parseObject(params);
        String sn = map.get("sn").toString();
        String procInsId = map.get("procInsId").toString();

        String realServiceUrl = Constants.BPMCENTER_URL + "/collBack";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;
        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);

        CallBackResult callBackResult = new CallBackResult();
        callBackResult.setProcInstGuid("");
        callBackResult.setProcInstID(procInsId);
        callBackResult.setSN(sn);
        callBackResult.setMonitorGuid("");
        SubmitActionType submitActionType = SubmitActionType.getStart();
        callBackResult.setActionType(submitActionType);
        callBackResult.setException("");
        ExecuteResultType executeResultType = ExecuteResultType.getSuccessfull();
        callBackResult.setExecuteState(executeResultType);
//        callBackResult.setProcessInstInfo(null);
        callBackResult.setSubmitRouteXML("");

        //调用远程接口
        result = restClient.postCgnVoForRest(url, header, callBackResult);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;

    }

    /**********************************
     * 用途说明: 退回接口
     * 参数说明 map
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult rollBackAction(Map map) throws Exception {
        String procInsId = map.get("procInstId").toString();
        String sn = map.get("sn").toString();
        String deal_suggest = map.get("deal_suggest").toString();
        String copygive = "";
        String slotCount = map.get("slotCount").toString();
        String mergeTask = map.get("mergeTask").toString();

        //找到原来节点的审批人进行设置
        String[] backMan = map.get("backMan").toString().split(",");
        String[] backManName = map.get("backManName").toString().split(",");

        String nowAct = map.get("now_deal_act").toString();
        String backAct = map.get("backAct").toString();

        if(!StringUtils.isEmpty(map.get("copygive"))){
//            copygive = map.get("copygive").toString();
            JSONArray array = (JSONArray) map.get("copygive");
            copygive = org.apache.commons.lang.StringUtils.join(array,',');
        }
        if(!StringUtils.isEmpty(map.get("deal_suggest"))){
            deal_suggest = map.get("deal_suggest").toString();
        }

        String realServiceUrl = Constants.BPMCENTER_URL + "/rollbackaction";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;
        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);
        //参数配置
        Map backMap = new HashMap<>();
        RollBackInfo backInfo = new RollBackInfo();
        backMap.put("requestConditionVO",requestConditionVO);
        backMap.put("rollBackInfo",backInfo);

        //设置回退人信息
        User[] users = new User[backMan.length];
        User user = new User();
        //拼接调用接口需要的参数
        for (int i = 0; i < backMan.length; i++) {
            user.setAccount(backMan[i]);
            user.setAppTaskID("");
            user.setAppTaskTitle("");
            user.setIsHidden("false");
            user.setDeptID("");
            user.setIsMobile("false");
            user.setIsRenew("false");
            user.setIsUserNotify("false");
            user.setLastDueTime(transDate(new Date()));
            user.setOldActInstDest("0");
            user.setOperationType("2");
            user.setSenderUserAccent(CurrentUser.getUser());
            user.setSenderUserDeptID("");
            user.setSnGroup("");
            user.setStartTime(transDate(new Date()));
            user.setUserChsName(backManName[i]);
            users[i] = user;
            user = new User();
        }

        Step step =  new Step();
        step.setActApproveGuid("");
        step.setMergeTask(mergeTask);
        step.setSlotCount(slotCount);
        step.setSlotGuid("");
        step.setUsers(users);

        Route route = new Route();
        route.setCurrentStep("0");
        route.setGuidCode("");
        route.setImpersonateUser(CurrentUser.getUser());
        route.setIsActNotify("false");
        route.setSnGroup("");
        route.setSourceActMetaData(nowAct);
        route.setSteps(new Step[]{step});
        route.setTargetActMetaData(backAct);

        RouteInfo routeInfo = new RouteInfo();
        routeInfo.setIsRouteNotify("false");
        routeInfo.setLineRuleIsFirst("false");
        routeInfo.setProcInstID(procInsId);
        routeInfo.setRoutes(new Route[]{route});

        backInfo.setApproveUserAccount(CurrentUser.getUser());
        backInfo.setApproveUserChsName(CurrentUser.getUserRealName());
        backInfo.setApproveUserDeptID("");
        backInfo.setCallbackClassName("");
        backInfo.setComment(deal_suggest);
        backInfo.setIsFinishedSubProcess("false");
        backInfo.setOperationType("15");
        backInfo.setProcInstID(procInsId);
        backInfo.setWorkID(sn);
        backInfo.setRouteInfo(routeInfo);

        //要先处理抄送，提交流程
        ArrayList idList = new ArrayList();
        ArrayList nameList = new ArrayList();
        ApiResult copySendResult = null;
        if(!StringUtils.isEmpty(copygive)){
            HashMap sendMap = new HashMap();
            sendMap.put("dealSuggest",deal_suggest);//处理意见
            sendMap.put("procInstId",procInsId);//流程实例
            sendMap.put("sourceAct",nowAct);//当前节点  020
            sendMap.put("targetAct",backAct);//下一节点 030
            sendMap.put("sn",sn);
            sendMap.put("slotCount",slotCount);
            sendMap.put("mergeTask",mergeTask);
            JSONArray array = (JSONArray) map.get("copygive");//[pxmwxxx]xxx
            array.forEach(n -> {
                idList.add(n.toString().substring(1,n.toString().lastIndexOf(']')));
                nameList.add(n.toString().substring(n.toString().lastIndexOf(']')+1));
            });
            //map 保存数组会转换为Map
            sendMap.put("userIds", org.apache.commons.lang.StringUtils.join(idList,","));
            sendMap.put("userNames", org.apache.commons.lang.StringUtils.join(nameList,","));
            copySendResult = copySendWorkListItem(sendMap);
        }

        if("local".equals(devMode)) {
            List list = new ArrayList();
            list.add(map);
            ApiResult invoke = mockClient.invoke("bpmCenterServiceImpl", "rollBackAction", list, ApiResult.class,Map.class);
            if(!CODE.equals(invoke.getCode())){
                throw new Exception(MessageUtils.message("cud.bpmcenter.error",invoke.getMsg()));
            }
            return invoke;
        }

        //判断是否抄送成功
        if((copySendResult!= null && CODE.equals(copySendResult.getCode())) || StringUtils.isEmpty(copygive)){//存在抄送
            LOGGER.info("backMap:{}", new JSONObject().toJSONString(backMap));
            //调用远程接口
            result = restClient.postCgnVoForRest(url, header, backMap);
            if(!CODE.equals(result.getCode())){
                throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
            }else{
                //退回流程成功  处理邮件发送
                UserInfo loginUserInfo = currentUser.getCurrentUserDetail();
                SendEmails emails = iEmailCenterService.buildSendEmails(CurrentUser.getUser(),
                        StringUtils.toStringArray(idList), "SCP调试一体化工作平台待办任务提醒<br/>邮件内容:<br/>您好：SCP调试一体化工作平台有待办任务需要处理:"+map.get("procChName").toString() +
                                "<br/>访问地址：https://scp.cgnpc.com.cn/#/need_deal_task"+"<br/>此邮件为自动发送，无需回复<br/>"+
                                loginUserInfo.getUserDept()+":"+loginUserInfo.getDeptCodePath()+"("+loginUserInfo.getUserName()+")","",
                        backMan,map.get("procChName").toString());
                iEmailCenterService.sendEmail(emails);
            }
            return result;
        }else{
            throw new Exception(copySendResult.getMsg());
        }
    }

    /**********************************
     * 用途说明: 撤销接口
     * 参数说明 params
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult withdraw(String params) throws Exception {
        Map map = JSONObject.parseObject(params);
        String procInsId = map.get("procInstId").toString();

        String realServiceUrl = Constants.BPMCENTER_URL + "/withdraw";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;
        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);
        //设置传递参数
        WithdrawVO withdrawVO = new WithdrawVO();
        withdrawVO.setIsMobile("false");
        withdrawVO.setProcinstId(procInsId);
        withdrawVO.setRequestConditionVO(requestConditionVO);
        withdrawVO.setUser(CurrentUser.getUser());
        withdrawVO.setUserChsName(CurrentUser.getUserRealName());
        withdrawVO.setUserDeptId("");

        if("local".equals(devMode)) {
            String json = "{\n" +
                    "  \"responseId\": \"1\",\n" +
                    "  \"code\": \"200\",\n" +
                    "  \"msg\": \"成功\",\n" +
                    "  \"data\": null\n" +
                    "}";
            return JacksonUtil.readValue(json,ApiResult.class);
        }

        //调用远程接口
        result = restClient.postCgnVoForRest(url, header, withdrawVO);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明:附件运行状态
     * 参数说明
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult imsBpmFileStatus() throws Exception {
        String realServiceUrl = Constants.BPMCENTER_URL + "/imsBpmFileStatus";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;
        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);

        //调用远程接口
        result = restClient.getCgnVoForRest(url,header,null);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明:流程中心健康检查
     * 参数说明
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult healthCheck() throws Exception {
        String realServiceUrl = Constants.BPMCENTER_URL + "/healthcheck";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;
        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);

        //调用远程接口
        result = restClient.getCgnVoForRest(url,header,null);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 获得代理列表
     * 参数说明 paramsMap
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult getDelegateList(Map paramsMap) throws Exception {
        Integer pageIndex = Integer.parseInt(paramsMap.get("pageIndex").toString());
        Integer pageSize = Integer.parseInt(paramsMap.get("pageSize").toString());
        //设置传递参数
        Map map = new HashMap();
        map.put("direction",0);
        map.put("requestConditionVO",requestConditionVO);
        map.put("startPage",pageIndex);
        map.put("pageSize",pageSize);
        map.put("totalCount",0);
        map.put("totalPage",0);
        List<Integer> fields = new ArrayList<Integer>();
        if("1".equals(paramsMap.get("type").toString())){
            fields.add(DelegateSettingField.FromUser.ordinal());
        }else{
            fields.add(DelegateSettingField.ToUser.ordinal());
        }
        List<Integer> logicals = new ArrayList<Integer>(){{add(QueryLogical.Empty.ordinal());}};
        List<Integer> operatoers = new ArrayList<Integer>(){{add(QueryOperator.Equal.ordinal());}};
        List<Integer> orderBys = new ArrayList<Integer>(){{add(DelegateSettingField.CreateDate.ordinal());}};
        List<Object> values = new ArrayList<Object>(){{add(CurrentUser.getUser());}};

        map.put("field",fields);
        map.put("logical",logicals);
        map.put("operatoer",operatoers);
        map.put("orderBys",orderBys);
        map.put("value",values);

        String realServiceUrl = Constants.BPMCENTER_URL + "/getdelegatesettingresult";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;
        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);

        //调用远程接口
        result = restClient.postCgnVoForRest(url,header,map);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 新增全部代理
     * 参数说明 params
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult addDelegates(String params) throws Exception {
        JSONObject paramsMap = JSONObject.parseObject(params);
        Date beginTime = paramsMap.getDate("beginTime");
        Date endTime = paramsMap.getDate("endTime");
        String userName = paramsMap.get("delegateUser").toString();
        String userId = paramsMap.get("delegateUserId").toString();
        String procName = paramsMap.get("procName").toString();
        String procFullName = paramsMap.get("procFullName").toString();

        Map sendMap = new HashMap();
        sendMap.put("appCode",appCode);
        sendMap.put("comment","");
        sendMap.put("createTime",DateUtils.getNowDate());
        sendMap.put("createUser",CurrentUser.getUser());
        sendMap.put("createUserName",CurrentUser.getUserRealName());
        sendMap.put("endTime",endTime);
        sendMap.put("fromUser",CurrentUser.getUser());
        sendMap.put("fromUserName",CurrentUser.getUserRealName());
        sendMap.put("id",0);
        sendMap.put("isEnabled",true);
        sendMap.put("isRedirect",true);
        sendMap.put("lastModifyDate",DateUtils.getNowDate());
        sendMap.put("lastModifyUser",CurrentUser.getUser());
        sendMap.put("lastModifyUserName",CurrentUser.getUserRealName());
        sendMap.put("processFullName",procFullName);
        sendMap.put("processName",procName);
        sendMap.put("requestConditionVO",requestConditionVO);
        sendMap.put("startTime",beginTime);
        sendMap.put("toUser",userId);
        sendMap.put("toUserName",userName);

        String realServiceUrl = Constants.BPMCENTER_URL + "/adddelegateusersetting";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;
        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);

        if("local".equals(devMode)) {
            String json = "{\n" +
                    "  \"responseId\": \"1\",\n" +
                    "  \"code\": \"200\",\n" +
                    "  \"msg\": \"成功\",\n" +
                    "  \"data\": [\n" +
                    "    {\n" +
                    "      \"appCode\": \"BMWS\",\n" +
                    "      \"isEnabled\": true,\n" +
                    "      \"isRedirect\": true,\n" +
                    "      \"endTime\": \"2019-12-17 02:24:20\",\n" +
                    "      \"createTime\": \"2019-12-17 02:24:20\",\n" +
                    "      \"createUser\": \"PXMWRYA\",\n" +
                    "      \"createUserName\": \"阮洋\",\n" +
                    "      \"fromUser\": \"pxmwzyp\",\n" +
                    "      \"fromUserName\": \"张膺鹏\",\n" +
                    "      \"lastModifyDate\": \"2019-12-17 02:24:20\",\n" +
                    "      \"lastModifyUser\": \"pxmwrya\",\n" +
                    "      \"lastModifyUserName\": \"阮洋\",\n" +
                    "      \"processFullName\": \"BMWS\\\\TestProcess\",\n" +
                    "      \"processName\": \"兑奖流程\",\n" +
                    "      \"toUser\": \"pxmwrya\",\n" +
                    "      \"toUserName\": \"阮洋\",\n" +
                    "      \"startTime\": \"2019-12-17 02:24:20\",\n" +
                    "      \"comment\": \"\",\n" +
                    "      \"id\": 18\n" +
                    "    }\n" +
                    "  ]\n" +
                    "}";
            return JacksonUtil.readValue(json,ApiResult.class);
        }

        //调用远程接口
        result = restClient.postCgnVoForRest(url,header,sendMap);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 新增代理
     * 参数说明 params
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult addDelegate(String params) throws Exception {
        JSONObject paramsMap = JSONObject.parseObject(params);

        Date beginTime = paramsMap.getDate("beginTime");
        Date endTime = paramsMap.getDate("endTime");
        String userName = paramsMap.get("delegateUser").toString();
        String userId = paramsMap.get("delegateUserId").toString();
        String procName = paramsMap.get("procName").toString();
        String procFullName = paramsMap.get("procFullName").toString();

        AddDelegateSettingVO settingVO = new AddDelegateSettingVO();
        DelegateSetting setting = new DelegateSetting();
        setting.setAppCode(appCode);
        setting.setComment("");
        setting.setCreateTime(DateUtils.getNowDate());
        setting.setCreateUser(CurrentUser.getUser());
        setting.setCreateUserName(CurrentUser.getUserRealName());
        setting.setEndTime(endTime);
        setting.setFromUser(CurrentUser.getUser());
        setting.setFromUserName(CurrentUser.getUserRealName());
        setting.setID(0);//这个暂时不知道什么意思;
        setting.setIsEnabled(true);
        setting.setIsRedirect(true);
        setting.setLastModifyDate(DateUtils.getNowDate());
        setting.setLastModifyUser(CurrentUser.getUser());
        setting.setLastModifyUserName(CurrentUser.getUserRealName());
        setting.setProcessFullName(procFullName);
        setting.setProcessName(procName);
        setting.setStartTime(beginTime);
        setting.setToUser(userId);
        setting.setToUserName(userName);

        List<DelegateSetting> settingList = new ArrayList<>();
        settingList.add(setting);
        settingVO.setDelegateSettings(settingList);
        settingVO.setRequestConditionVO(requestConditionVO);

        String realServiceUrl = Constants.BPMCENTER_URL + "/addDelegateSetting";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;
        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);

        //调用远程接口
        result = restClient.postCgnVoForRest(url,header,settingVO);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 待阅（不限流程状态）
     * 参数说明 paramsMap
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult getCopySendItemsListSecond(Map paramsMap) throws Exception {
        Integer pageIndex = Integer.parseInt(paramsMap.get("pageIndex").toString());
        Integer pageSize = Integer.parseInt(paramsMap.get("pageSize").toString());

        String realServiceUrl = Constants.BPMCENTER_URL + "/getCopySendItemsListSecond";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;
        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);
        //设置传递参数
        GetCopySendItemsListSecondVO secondVO = new GetCopySendItemsListSecondVO();
        secondVO.setRequestConditionVO(requestConditionVO);
        ToDoTaskQuery query = new ToDoTaskQuery();
        query.setApp(appCode);
        query.setImpersonateUser(CurrentUser.getUser());
        query.setWorkListItemType(2);//任务类型 待阅还是待办 这里应该是待阅 1代表待办 2代表待阅
        query.setDirection(QueryDirection.DESC);
        query.setConditions(null);
//        ToDoTaskFilter filter = new ToDoTaskFilter();
        List<ToDoTaskField> orderList = new ArrayList<>();
        orderList.add(ToDoTaskField.TaskStartTime);
        query.setOrderBys(orderList);

        QueryPaging paging = new QueryPaging();
        paging.setStartPage(pageIndex);
        paging.setPageSize(pageSize);
        query.setPageSetting(paging);
//        secondVO.setToDoTaskQuery(query);
        //调用远程接口
        result = restClient.postCgnVoForRest(url,header,secondVO);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 抄送(这个流程必须结束了)，产生待阅  待完成  //目前接口写的只是一个？
     * 参数说明 paramsMap
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult copySendWorkListItemSecond(Map paramsMap) throws Exception {
        String dealSuggest = paramsMap.get("dealSuggest").toString();
        String procInstId = paramsMap.get("procInstId").toString();
        String[] userIds =  paramsMap.get("userIds").toString().split(",");
        String[] userNames =  paramsMap.get("userNames").toString().split(",");

        String realServiceUrl = Constants.BPMCENTER_URL + "/copySendWorkListItemSecond";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;

        CgnRequestHeader header = null;
        ApiResult result = null;

        header = CgnHeader.getHeader(realServiceUrl,aepProperties);
        //设置传递参数
        CopySendWorkListItemSecondVO secondVO = new CopySendWorkListItemSecondVO();
        secondVO.setRequestConditionVO(requestConditionVO);

        Items items = new Items();
        items.setKey("");
        items.setValue("");

        ExtendMsgXML extendMsgXML = new ExtendMsgXML();
        extendMsgXML.setItems(items);

        NotifyMsgInfo notifyMsgInfo = new NotifyMsgInfo();
        notifyMsgInfo.setExtendMsgXML(extendMsgXML);
        notifyMsgInfo.setMessageTemplateID("");
        notifyMsgInfo.setNotifyTypes("");
        notifyMsgInfo.setSubject("");

        User[] users = new User[userIds.length];
        User user = new User();

        //拼接调用接口所需要的参数
        for (int i = 0; i < users.length; i++) {
            user.setAccount(userIds[i]);
            user.setAppTaskID("01");
            user.setAppTaskTitle("Test");
            user.setDeptID("");
            user.setIsHidden("false");
            user.setIsMobile("false");
            user.setIsRenew("false");
            user.setIsUserNotify("false");
            user.setLastDueTime(transDate(new Date()));
            user.setOldActInstDest("String");
            user.setOperationType("0");
            user.setSenderUserAccent(currentUser.getNowUser());
            user.setUserChsName(userNames[i]);
            user.setSenderUserDeptID("");
            user.setSnGroup("");
            user.setStartTime(transDate(new Date()));

            users[i] = user;
            user = new User();
        }

        CopySendUsers copySendUsers = new CopySendUsers();
        copySendUsers.setUser(user);

        CopyProcInfo copyProcInfo = new CopyProcInfo();
        copyProcInfo.setAction("0");
        copyProcInfo.setCallbackClassName("");
        copyProcInfo.setComment(dealSuggest);//处理意见
        copyProcInfo.setNotifyMsgInfo(notifyMsgInfo);
        copyProcInfo.setNotifyType("0");
        copyProcInfo.setProcInstID(procInstId);
        copyProcInfo.setSubmitUser(CurrentUser.getUser());
        copyProcInfo.setSubmitUserChName(CurrentUser.getUserRealName());
        copyProcInfo.setUserDept("");
        copyProcInfo.setCopySendUsers(users);

        secondVO.setCopyProcInfo(copyProcInfo);
        //调用远程接口
        result = restClient.postCgnVoForRest(url,header,secondVO);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 抄送功能
     * 参数说明 paramsMap
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult copySendWorkListItem(Map paramsMap) throws Exception {

        String dealSuggest = paramsMap.get("dealSuggest").toString();
        String procInstId = paramsMap.get("procInstId").toString();
        String sourceAct = paramsMap.get("sourceAct").toString();
        String targetAct = paramsMap.get("targetAct").toString();
        String[] userIds =  paramsMap.get("userIds").toString().split(",");
        String[] userNames = paramsMap.get("userNames").toString().split(",");
        String mergeTask = paramsMap.get("mergeTask").toString();
        String slotCount = paramsMap.get("slotCount").toString();
        String sn = paramsMap.get("sn").toString();

        String realServiceUrl = Constants.BPMCENTER_URL + "/copySendWorkListItem";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;

        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);
        //设置传递参数
        CopySendWorkListItemVO copySendWorkListItemVO = new CopySendWorkListItemVO();
        copySendWorkListItemVO.setRequestConditionVO(requestConditionVO);

        User[] users = new User[userIds.length];//抄送多个
        User tempUser = new User();
        //拼接调用接口需要的参数
        for (int i = 0; i < users.length; i++) {
            tempUser.setAccount(userIds[i]);
            tempUser.setAppTaskID("01");
            tempUser.setAppTaskTitle("Test");
            tempUser.setDeptID("");
            tempUser.setIsHidden("false");
            tempUser.setIsMobile("false");
            tempUser.setIsRenew("false");
            tempUser.setIsUserNotify("false");
            tempUser.setLastDueTime(transDate(new Date()));
            tempUser.setOldActInstDest("0");
            tempUser.setOperationType("1");
            tempUser.setSenderUserAccent(CurrentUser.getUser());
            tempUser.setSenderUserDeptID("");
            tempUser.setSnGroup("");
            tempUser.setStartTime(transDate(new Date()));
            tempUser.setUserChsName(userNames[i]);
            users[i] = tempUser;
            tempUser = new User();
        }

        Step step = new Step();
        step.setSlotGuid("");//
        step.setSlotCount(slotCount);//会签规则
        step.setMergeTask(mergeTask);//合并任务
        step.setActApproveGuid("");//
        step.setUsers(users);

        //这里应该是存放多个 用于抄送
        Route route = new Route();
        route.setGuidCode("");//guidcode
        route.setSourceActMetaData(sourceAct);
        route.setTargetActMetaData(targetAct);
        route.setImpersonateUser(CurrentUser.getUser());//
        route.setCurrentStep("0");//当前步骤
        route.setIsActNotify("false");//
        route.setSnGroup("");//
        route.setSteps(new Step[]{step});

        RouteInfo routeInfo = new RouteInfo();
        routeInfo.setProcInstID(procInstId);
        routeInfo.setIsRouteNotify("false");
        routeInfo.setLineRuleIsFirst("false");
        routeInfo.setRoutes(new Route[]{route});

        //请填充user内容  这里给当前登录用户?  submitProcInfo copySendUsers
        User user = new User();
        user.setAccount(currentUser.getNowUser());
        user.setAppTaskID("01");
        user.setAppTaskTitle("test");
        user.setDeptID("");
        user.setIsHidden("false");
        user.setIsMobile("false");
        user.setIsRenew("false");
        user.setIsUserNotify("false");
        user.setLastDueTime(transDate(new Date()));
        user.setOldActInstDest("0");
        user.setOperationType("1");
        user.setSenderUserAccent(CurrentUser.getUser());
        user.setSenderUserDeptID("");
        user.setSnGroup("");
        user.setStartTime(transDate(new Date()));
        user.setUserChsName(CurrentUser.getUserRealName());


        SubmitProcInfo submitProcInfo = new SubmitProcInfo();
        submitProcInfo.setAction("11");
        submitProcInfo.setSN(sn);//任务编号，当前待办的workId
        submitProcInfo.setSubmitUser(CurrentUser.getUser());
        submitProcInfo.setSubmitUserChName(CurrentUser.getUserRealName());
        submitProcInfo.setUserDept("");//当前用户部门编号
        submitProcInfo.setProcInstID(procInstId);//流程实例编号
        submitProcInfo.setCallbackClassName("");//回调方法接口名称
        submitProcInfo.setComment(dealSuggest);//处理意见
        submitProcInfo.setIsImmediacyEnd("false");//是否快速结束流程，提交到END时有效
        submitProcInfo.setNotifyType("0");
        submitProcInfo.setIsCopySend("false");
        submitProcInfo.setCopyType("0");//流程结束后保留待阅任务
        submitProcInfo.setIsFinishedGroup("false");
        submitProcInfo.setSuspended("false");
        submitProcInfo.setCopySendUsers(users);
        submitProcInfo.setRouteInfo(routeInfo);

        copySendWorkListItemVO.setSubmitProcInfo(submitProcInfo);

        //调用远程接口
        result = restClient.postCgnVoForRest(url,header,copySendWorkListItemVO);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 获取用户代理结果
     * 参数说明 paramsMap
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult getDelegateListByUser(Map paramsMap) throws Exception {
        Integer pageIndex = Integer.parseInt(paramsMap.get("pageIndex").toString());
        Integer pageSize = Integer.parseInt(paramsMap.get("pageSize").toString());

        String realServiceUrl = Constants.BPMCENTER_URL + "/getdelegateusersettingresult";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;

        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);

        //设置传递参数
        Map map = new HashMap();
        map.put("direction",0);
        map.put("requestConditionVO",requestConditionVO);
        map.put("startPage",pageIndex);
        map.put("pageSize",pageSize);
        map.put("totalCount",0);
        map.put("totalPage",0);
        //判断是委托还是受托
        List<Integer> fields = new ArrayList<Integer>();
        if("1".equals(paramsMap.get("type").toString())){
            fields.add(DelegateSettingField.FromUser.ordinal());
        }else{
            fields.add(DelegateSettingField.ToUser.ordinal());
        }
        List<Integer> logicals = new ArrayList<Integer>(){{add(QueryLogical.Empty.ordinal());}};
        List<Integer> operatoers = new ArrayList<Integer>(){{add(QueryOperator.Equal.ordinal());}};
        List<Integer> orderBys = new ArrayList<Integer>(){{add(DelegateSettingField.CreateDate.ordinal());}};
        List<Object> values = new ArrayList<Object>(){{add(CurrentUser.getUser());}};
        map.put("field",fields);
        map.put("logical",logicals);
        map.put("operatoer",operatoers);
        map.put("orderBys",orderBys);
        map.put("value",values);

        if("local".equals(devMode)) {
//            String json = "{\n" +
//                    "  \"responseId\": \"1\",\n" +
//                    "  \"code\": \"200\",\n" +
//                    "  \"msg\": \"成功\",\n" +
//                    "  \"data\": {\n" +
//                    "    \"resultData\": [\n" +
//                    "      {\n" +
//                    "        \"processFullName\": \"\",\n" +
//                    "        \"fromUser\": \"pxmwzyp\",\n" +
//                    "        \"lastModifyUserName\": \"\",\n" +
//                    "        \"createUserName\": \"阮洋\",\n" +
//                    "        \"appCode\": \"BMWS\",\n" +
//                    "        \"fromUserName\": \"张膺鹏\",\n" +
//                    "        \"lastModifyUser\": \"\",\n" +
//                    "        \"toUser\": \"pxmwrya\",\n" +
//                    "        \"isRedirect\": false,\n" +
//                    "        \"createTime\": {\n" +
//                    "          \"date\": 1,\n" +
//                    "          \"hours\": 0,\n" +
//                    "          \"seconds\": 0,\n" +
//                    "          \"month\": 0,\n" +
//                    "          \"timezoneOffset\": -480,\n" +
//                    "          \"year\": -1899,\n" +
//                    "          \"minutes\": 0,\n" +
//                    "          \"time\": -62135798400000,\n" +
//                    "          \"day\": 6\n" +
//                    "        },\n" +
//                    "        \"processName\": \"\",\n" +
//                    "        \"isEnabled\": true,\n" +
//                    "        \"toUserName\": \"阮洋\",\n" +
//                    "        \"comment\": \"\",\n" +
//                    "        \"createUser\": \"PXMWRYA\",\n" +
//                    "        \"startTime\": {\n" +
//                    "          \"date\": 17,\n" +
//                    "          \"hours\": 11,\n" +
//                    "          \"seconds\": 29,\n" +
//                    "          \"month\": 11,\n" +
//                    "          \"timezoneOffset\": -480,\n" +
//                    "          \"year\": 119,\n" +
//                    "          \"minutes\": 3,\n" +
//                    "          \"time\": 1576551809000,\n" +
//                    "          \"day\": 2\n" +
//                    "        },\n" +
//                    "        \"ID\": 17,\n" +
//                    "        \"endTime\": {\n" +
//                    "          \"date\": 17,\n" +
//                    "          \"hours\": 11,\n" +
//                    "          \"seconds\": 29,\n" +
//                    "          \"month\": 11,\n" +
//                    "          \"timezoneOffset\": -480,\n" +
//                    "          \"year\": 119,\n" +
//                    "          \"minutes\": 3,\n" +
//                    "          \"time\": 1576551809000,\n" +
//                    "          \"day\": 2\n" +
//                    "        },\n" +
//                    "        \"lastModifyDate\": {\n" +
//                    "          \"date\": 1,\n" +
//                    "          \"hours\": 0,\n" +
//                    "          \"seconds\": 0,\n" +
//                    "          \"month\": 0,\n" +
//                    "          \"timezoneOffset\": -480,\n" +
//                    "          \"year\": -1899,\n" +
//                    "          \"minutes\": 0,\n" +
//                    "          \"time\": -62135798400000,\n" +
//                    "          \"day\": 6\n" +
//                    "        }\n" +
//                    "      }\n" +
//                    "    ],\n" +
//                    "    \"page\": {\n" +
//                    "      \"startPage\": 1,\n" +
//                    "      \"totalPage\": 0,\n" +
//                    "      \"pageSize\": 1,\n" +
//                    "      \"totalCount\": 2\n" +
//                    "    }\n" +
//                    "  }\n" +
//                    "}";
//            return JacksonUtil.readValue(json,ApiResult.class);
            List list = new ArrayList();
            list.add(paramsMap);
            ApiResult invoke = mockClient.invoke("bpmCenterServiceImpl", "getDelegateListByUser", list, ApiResult.class,Map.class);
            return invoke;
        }

        //调用远程接口
        result = restClient.postCgnVoForRest(url,header,map);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 获取待阅(抄送列表)
     * 参数说明 paramsMap
     * 返回值说明:
     ***********************************/
    public ApiResult getCopySendItemsList(Map paramsMap) throws Exception{
        Integer pageIndex = Integer.parseInt(paramsMap.get("pageIndex").toString());
        Integer pageSize = Integer.parseInt(paramsMap.get("pageSize").toString());

        String realServiceUrl = Constants.BPMCENTER_URL + "/getCopySendItemsList";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;

        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);
        //设置传递参数
        CopySendItemsListVO copySendItemsListVO = new CopySendItemsListVO();
        copySendItemsListVO.setRequestConditionVO(requestConditionVO);
        BpmToDoTaskQuery toDoTaskQuery = new BpmToDoTaskQuery();
        toDoTaskQuery.setApp(appCode);
        ArrayList<BpmToDoTaskFilter> filterList = new ArrayList<>();
        if(!StringUtils.isEmpty("searchType") && !paramsMap.get("searchType").toString().equals("0")){
            //说明有查询条件
            HashMap searchMap = (HashMap) paramsMap.get("searchParams");

            Set<Map.Entry> set = searchMap.entrySet();
            BpmToDoTaskFilter toDoTaskFilter = new BpmToDoTaskFilter();
            Iterator<Map.Entry> it = set.iterator();
            //条件查询 参数
            for (int i = 0; it.hasNext() ; i++) {
                Map.Entry entry = it.next();
                if(!StringUtils.isEmpty(entry.getValue()) && !entry.getValue().toString().trim().equals("")){
                    toDoTaskFilter.setField(ToDoTaskField.valueOf(entry.getKey().toString()));//找到字段
                    toDoTaskFilter.setOperatoer(QueryOperator.Equal);
                    toDoTaskFilter.setValue(entry.getValue().toString());//找到值
                    if (filterList.size() == 0) {
                        toDoTaskFilter.setLogical(QueryLogical.Empty);
                    } else {
                        toDoTaskFilter.setLogical(QueryLogical.And);
                    }
                    filterList.add(toDoTaskFilter);
                    toDoTaskFilter = new BpmToDoTaskFilter();
                }else{
                    //表示值为空字符串或者 null
                    toDoTaskFilter = new BpmToDoTaskFilter();
                }
            }
            if (filterList.size() != 0){
                toDoTaskQuery.setConditions(filterList);
            }else {
                toDoTaskQuery.setConditions(null);
            }
        }else{
            toDoTaskQuery.setConditions(null);
        }
        toDoTaskQuery.setConditions(filterList);
        toDoTaskQuery.setDirection(QueryDirection.DESC);
        List<ToDoTaskField> orderList = new ArrayList<ToDoTaskField>();
        orderList.add(ToDoTaskField.TaskStartTime);
        toDoTaskQuery.setOrderBys(orderList);
        toDoTaskQuery.setImpersonateUser(CurrentUser.getUser());
        toDoTaskQuery.setWorkListItemType(0);
        copySendItemsListVO.setToDoTaskQuery(toDoTaskQuery);
        QueryPaging queryPaging = new QueryPaging();
        queryPaging.setPageSize(pageSize);
        queryPaging.setStartPage(pageIndex);
        toDoTaskQuery.setPageSetting(queryPaging);

        if("local".equals(devMode)) {
//            String json = "{\n" +
//                    "  \"responseId\": \"1\",\n" +
//                    "  \"code\": \"200\",\n" +
//                    "  \"msg\": \"成功\",\n" +
//                    "  \"data\": {\n" +
//                    "    \"Paging\": {\n" +
//                    "      \"pageSize\": 10,\n" +
//                    "      \"totalPage\": 1,\n" +
//                    "      \"startPage\": 1,\n" +
//                    "      \"totalCount\": 1\n" +
//                    "    },\n" +
//                    "    \"ToDoTasks\": [\n" +
//                    "      {\n" +
//                    "        \"appCode\": null,\n" +
//                    "        \"activityID\": \"11115\",\n" +
//                    "        \"workListItemType\": \"3\",\n" +
//                    "        \"sn\": \"364545\",\n" +
//                    "        \"folio\": \"关于测试邮件获奖的流程\",\n" +
//                    "        \"activityName\": \"020_审批信息\",\n" +
//                    "        \"processStartTime\": \"2019/8/26 10:15:32\",\n" +
//                    "        \"startUser\": \"PXMWRYA\",\n" +
//                    "        \"startUserCN\": \"PXMWRYA阮洋\",\n" +
//                    "        \"hasRead\": false,\n" +
//                    "        \"procInstID\": \"77805\",\n" +
//                    "        \"processFullName\": \"BMWS\\\\TestProcess\",\n" +
//                    "        \"processName\": \"兑奖流程\",\n" +
//                    "        \"deptID\": \"\",\n" +
//                    "        \"operationType\": 11,\n" +
//                    "        \"appTaskID\": null,\n" +
//                    "        \"appTaskTitle\": null,\n" +
//                    "        \"lastDueTime\": \"0001-01-01 00:00:00\",\n" +
//                    "        \"procGuid\": \"0207376dab484a9ab74a041709a8406e\",\n" +
//                    "        \"procID\": \"1116\",\n" +
//                    "        \"actionerAccount\": null,\n" +
//                    "        \"actionerChsName\": null,\n" +
//                    "        \"actionerDeptID\": null,\n" +
//                    "        \"delegateAccount\": null,\n" +
//                    "        \"delegateChsName\": null,\n" +
//                    "        \"dflist\": [\n" +
//                    "          {\n" +
//                    "            \"key\": \"Field1\",\n" +
//                    "            \"value\": \"\"\n" +
//                    "          },\n" +
//                    "          {\n" +
//                    "            \"key\": \"Field2\",\n" +
//                    "            \"value\": \"\"\n" +
//                    "          },\n" +
//                    "          {\n" +
//                    "            \"key\": \"Field3\",\n" +
//                    "            \"value\": \"\"\n" +
//                    "          },\n" +
//                    "          {\n" +
//                    "            \"key\": \"Field4\",\n" +
//                    "            \"value\": \"\"\n" +
//                    "          },\n" +
//                    "          {\n" +
//                    "            \"key\": \"Field5\",\n" +
//                    "            \"value\": \"\"\n" +
//                    "          },\n" +
//                    "          {\n" +
//                    "            \"key\": \"Field6\",\n" +
//                    "            \"value\": \"\"\n" +
//                    "          }\n" +
//                    "        ],\n" +
//                    "        \"formInstID\": \"50d72848454f4d95ab3b0864b357580f\",\n" +
//                    "        \"isDelegated\": false,\n" +
//                    "        \"isProcessing\": false,\n" +
//                    "        \"preActivitySender\": \"PXMWRYA\",\n" +
//                    "        \"preActivitySenderName\": null,\n" +
//                    "        \"preActName\": \"020_审批信息\",\n" +
//                    "        \"taskFlag\": \"1\",\n" +
//                    "        \"taskStartTime\": \"2019/8/26 11:19:41\",\n" +
//                    "        \"taskType\": null,\n" +
//                    "        \"priority\": \"-1\"\n" +
//                    "      }\n" +
//                    "    ]\n" +
//                    "  }\n" +
//                    "}";
//            return JacksonUtil.readValue(json,ApiResult.class);
            List list = new ArrayList();
            list.add(paramsMap);
            ApiResult invoke = mockClient.invoke("bpmCenterServiceImpl", "getCopySendItemsList", list, ApiResult.class,Map.class);
            return invoke;
        }

        //调用远程接口
        result = restClient.postCgnVoForRest(url,header,copySendItemsListVO);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 待阅提交
     * 参数说明 paramsMap
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult copysenditemsubmitSecond(Map paramsMap) throws Exception {
        String comment = paramsMap.get("comment").toString();
        String workId = paramsMap.get("workId").toString();

        String realServiceUrl = Constants.BPMCENTER_URL + "/copysenditemsubmit02";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;

        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);
        //设置传递参数
        HashMap map = new HashMap();
        map.put("comment",comment);
        map.put("requestConditionVO",requestConditionVO);
        map.put("submitUser",CurrentUser.getUser());
        map.put("submitUserChName",CurrentUser.getUserRealName());
        map.put("userDept","");
        map.put("workID",workId);

        if("local".equals(devMode)) {
            String json = "{\n" +
                    "  \"responseId\": \"1\",\n" +
                    "  \"code\": \"200\",\n" +
                    "  \"msg\": \"成功\",\n" +
                    "  \"data\": null\n" +
                    "}";
            return JacksonUtil.readValue(json,ApiResult.class);
        }

        //调用远程接口
        result = restClient.postCgnVoForRest(url,header,map);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 删除代理用户设置
     * 参数说明 paramsMap
     * 返回值说明:
     ***********************************/
    public ApiResult delDelegateUserSetting(Map paramsMap) throws Exception{
        Integer pid = Integer.parseInt(paramsMap.get("pid").toString());

        String realServiceUrl = Constants.BPMCENTER_URL + "/deldelegateusersetting";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;

        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);
        //设置传递参数
        DelDelegateUserSettingVO delDelegateUserSettingVO = new DelDelegateUserSettingVO();
        delDelegateUserSettingVO.setPid(pid);
        delDelegateUserSettingVO.setRequestConditionVO(requestConditionVO);

        if("local".equals(devMode)) {
            String json = "{\n" +
                    "  \"responseId\": \"1\",\n" +
                    "  \"code\": \"200\",\n" +
                    "  \"msg\": \"成功\",\n" +
                    "  \"data\": \"删除代理用户设置成功\"\n" +
                    "}";
            return JacksonUtil.readValue(json,ApiResult.class);
        }

        //调用远程接口
        result = restClient.postCgnVoForRest(url,header,delDelegateUserSettingVO);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 删除代理设置
     * 参数说明 paramsMap
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult deldelegatesetting(Map paramsMap) throws Exception {
        Integer pid = Integer.parseInt(paramsMap.get("pid").toString());

        String realServiceUrl = Constants.BPMCENTER_URL + "/deldelegatesetting";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;

        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);
        //设置传递参数
        DelDelegateSettingVO settingVO = new DelDelegateSettingVO();
        settingVO.setPid(pid);
        settingVO.setRequestConditionVO(requestConditionVO);
        //调用远程接口
        result = restClient.postCgnVoForRest(url,header,settingVO);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 分页查询我的草稿列表
     * 参数说明 paramsMap
     * 返回值说明:
     ***********************************/
    public ApiResult getDraftListByPaging(Map paramsMap) throws Exception{
        Integer pageIndex = Integer.parseInt(paramsMap.get("pageIndex").toString());
        Integer pageSize = Integer.parseInt(paramsMap.get("pageSize").toString());
        String procName = paramsMap.get("procName").toString();//流程名称

        String realServiceUrl = Constants.BPMCENTER_URL + "/getDraftListByPaging";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;

        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);
        //设置传递参数
        BpmDraftVO bpmDraftVO = new BpmDraftVO();
        bpmDraftVO.setProcessName(procName);//流程名称
        bpmDraftVO.setBpmDraftFieldList(Arrays.asList(BpmDraftField.create_time));
        bpmDraftVO.setBpmQueryDirection(BpmQueryDirection.DESC);
        BpmQueryPaging paging = new BpmQueryPaging();
        paging.setStartPage(pageIndex);
        paging.setPageSize(pageSize);
        bpmDraftVO.setBpmQueryPaging(paging);
        bpmDraftVO.setTenantId(appId);
        //查询条件
        if(!StringUtils.isEmpty(paramsMap.get("launchTime"))){
            List timeList = (ArrayList)paramsMap.get("launchTime");
            if(timeList.size() >= 2){
                bpmDraftVO.setCreateTime(DateUtils.dateTime("yyyy-MM-dd",timeList.get(0).toString()));
                bpmDraftVO.setCreateTimeEnd(DateUtils.dateTime("yyyy-MM-dd",timeList.get(1).toString()));
            }
        }
        if(!StringUtils.isEmpty(paramsMap.get("folio"))){
            bpmDraftVO.setFolio(paramsMap.get("folio").toString());
        }

        //设置草稿发起人 我的草稿指我的
        bpmDraftVO.setStartUser(CurrentUser.getUser());

        if("local".equals(devMode)) {
            List list = new ArrayList();
            list.add(paramsMap);
            ApiResult invoke = mockClient.invoke("bpmCenterServiceImpl", "getDraftListByPaging", list, ApiResult.class,Map.class);
            return invoke;
        }

        ////调用远程接口
        result = restClient.postCgnVoForRest(url,header,bpmDraftVO);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 新增我的草稿
     * 参数说明 paramsMap
     * 返回值说明:
     ***********************************/
    public ApiResult addDraft(Map paramsMap) throws Exception{
        //前端传递的参数
        JSONArray nextDealer = (JSONArray) paramsMap.get("next_deal_name");//下一步处理人
        //取员工号和姓名
        List<String> nextDealerIdList = new ArrayList<>();
        List<String> nextDealerNameList = new ArrayList<>();
        nextDealer.forEach(n -> {
            nextDealerIdList.add(n.toString().substring(1,n.toString().indexOf("]")));
            nextDealerNameList.add(n.toString().substring(n.toString().lastIndexOf("]")+1));
        });
        String actName = paramsMap.get("act_name").toString();//当前环节名称
        String isMergeTask = paramsMap.get("mergeTask").toString();//是否合并任务
        String procSetId = paramsMap.get("procSetId").toString();//流程集ID
        String fullName = paramsMap.get("fullName").toString();//流程名称
        String procName = paramsMap.get("procChName").toString();//流程名称
        String slotCount = paramsMap.get("slotCount").toString();//会签规则
        String sourceAct = paramsMap.get("now_deal_act").toString();//发起环节编号
        String targetAct =paramsMap.get("next_deal_act").toString();//目标环节编号
        String formNoId = paramsMap.get("appFormId").toString();//业务ID

        String realServiceUrl = Constants.BPMCENTER_URL + "/addDraft";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;
        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);
        //设置传递参数
        BpmDraftVO draftVO = new BpmDraftVO();
        draftVO.setAccount(org.apache.commons.lang.StringUtils.join(nextDealerIdList,","));
//        draftVO.setAccount(nextDealerIdList.get(0));//下一步处理人 目前设置为一个，应该是多选
        draftVO.setActivityName(actName);//流程环节名称
        draftVO.setAppTaskID("");//任务编号
        draftVO.setAppTaskTitle("");//任务主题
        draftVO.setCallbackClassName("");//任务回调方法名
        draftVO.setCreateTime(new Date());//
        draftVO.setCreateTimeEnd(new Date());//
        draftVO.setDeptID("");//待处理人部门编号
        draftVO.setDr("");//
        draftVO.setFolio("用户["+CurrentUser.getUser()+"]"+CurrentUser.getUserRealName()+"于"+
                DateUtils.dateTimeNow("yyyy-MM-dd")+"发起"+procName);//流程主题
        draftVO.setFormNo(formNoId);//业务表单ID
        draftVO.setLastDueTime(DateUtils.dateTimeNow("yyyy-MM-dd'T'HH:mm:ss"));//要求完成期限
        draftVO.setMergeTask(isMergeTask);//是否合并任务
        draftVO.setProcInstID("0");//流程实例ID  发起流程时默认为0
        draftVO.setProcSetID(procSetId);//流程集ID
        draftVO.setProcessFullName(fullName);//流程名称
        draftVO.setProcessName(procName);//流程名称
        draftVO.setProcessStartTime(DateUtils.dateTimeNow("yyyy-MM-dd'T'HH:mm:ss"));//流程发起时间
        draftVO.setRequestId(null);
        draftVO.setSenderUserAccent(CurrentUser.getUser());//提交人工号
        draftVO.setSlotCount(slotCount);//会签规则
        draftVO.setSourceActMetaData(sourceAct);//发起环节编号
        draftVO.setStartDept("");//发起人部门编号
        draftVO.setStartTime(DateUtils.dateTimeNow("yyyy-MM-dd'T'HH:mm:ss"));//使用流程发起时间
        draftVO.setStartUser(CurrentUser.getUser());//发起人员工号
        draftVO.setStartUserCN(CurrentUser.getUserRealName());//发起人中文名称
        draftVO.setTargetActMetaData(targetAct);//目标环节编号
        draftVO.setTenantId(appId);//
        draftVO.setUpdateTime(new Date());//
        draftVO.setUpdateTimeEnd(new Date());//
//        draftVO.setUserChsName(nextDealerNameList.get(0));//待处理人中文名称
        draftVO.setUserChsName(org.apache.commons.lang.StringUtils.join(nextDealerNameList,","));

        if("local".equals(devMode)) {
//            String json = "{\n" +
//                    "    \"responseId\": \"1\",\n" +
//                    "    \"code\": \"200\",\n" +
//                    "    \"msg\": \"成功 \",\n" +
//                    "    \"data\": null\n" +
//                    "}\n";
//            return JacksonUtil.readValue(json,ApiResult.class);
            List list = new ArrayList();
            list.add(paramsMap);
            ApiResult invoke = mockClient.invoke("bpmCenterServiceImpl", "addDraft", list, ApiResult.class,Map.class);
            if(!CODE.equals(invoke.getCode())){
                throw new Exception(MessageUtils.message("cud.bpmcenter.error",invoke.getMsg()));
            }
            return invoke;
        }

        ////调用远程接口
        result = restClient.postCgnVoForRest(url,header,draftVO);
        if(!CODE.equals(result.getCode())){
            throw new Exception(result.getMsg());
        }
        return result;
    }

    /**********************************
     * 用途说明: 删除我的草稿
     * 参数说明 paramsMap
     * 返回值说明:
     ***********************************/
    public ApiResult deleteMyDraft(Map paramsMap) throws Exception{
        //我的草稿的主键
        String idList = paramsMap.get("id").toString();

        if("local".equals(devMode)) {
            List list = new ArrayList();
            list.add(paramsMap);
            ApiResult invoke = mockClient.invoke("bpmCenterServiceImpl", "deleteMyDraft", list, ApiResult.class,Map.class);
            if(!CODE.equals(invoke.getCode())){
                throw new Exception(MessageUtils.message("cud.bpmcenter.error",invoke.getMsg()));
            }
            return invoke;
//            String json = "{\n" +
//                    "    \"responseId\": \"1\",\n" +
//                    "    \"code\": \"200\",\n" +
//                    "    \"msg\": \"成功\",\n" +
//                    "    \"data\": 1\n" +
//                    "}\n";
//            return JacksonUtil.readValue(json,ApiResult.class);
        }

        String realServiceUrl = Constants.BPMCENTER_URL + "/deleteDraftByIds?idList="+idList;
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;
        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);
        //调用远程接口
        result = restClient.postCgnVoForRest(url,header,null);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 更新我的草稿
     * 参数说明 paramsMap
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult updateDraft(Map paramsMap) throws Exception {
        ArrayList nextDealer = (ArrayList) paramsMap.get("next_deal_name");//下一步处理人
        //取员工号和姓名
        List<String> nextDealerIdList = new ArrayList<>();
        List<String> nextDealerNameList = new ArrayList<>();
        nextDealer.forEach(n -> {
            nextDealerIdList.add(n.toString().substring(1,n.toString().indexOf("]")));
            nextDealerNameList.add(n.toString().substring(n.toString().lastIndexOf("]")+1));
        });
        String id = paramsMap.get("draftId").toString();
        String actName = paramsMap.get("act_name").toString();//当前环节名称
        String isMergeTask = paramsMap.get("mergeTask").toString();//是否合并任务
        String procSetId = paramsMap.get("procSetId").toString();//流程集ID
        String fullName = paramsMap.get("fullName").toString();//流程名称
        String procName = paramsMap.get("procChName").toString();//流程名称
        String slotCount = paramsMap.get("slotCount").toString();//会签规则
        String sourceAct = paramsMap.get("now_deal_act").toString();//发起环节编号
        String targetAct =paramsMap.get("next_deal_act").toString();//目标环节编号
        String formNoId = paramsMap.get("appFormId").toString();//业务ID

        String realServiceUrl = Constants.BPMCENTER_URL + "/updateDraft";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;
        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);
        //设置传递参数
        BpmDraftVO draftVO = new BpmDraftVO();
        draftVO.setId(id);
//        draftVO.setAccount(nextDealerIdList.get(0));//下一步处理人 目前设置为一个，应该是多选
        draftVO.setAccount(org.apache.commons.lang.StringUtils.join(nextDealerIdList,","));
        draftVO.setActivityName(actName);//流程环节名称
        draftVO.setAppTaskID("");//任务编号
        draftVO.setAppTaskTitle("");//任务主题
        draftVO.setCallbackClassName("");//任务回调方法名
        draftVO.setCreateTime(new Date());//
        draftVO.setCreateTimeEnd(new Date());//
        draftVO.setDeptID("");//待处理人部门编号
        draftVO.setDr("");//
        draftVO.setFolio("用户["+CurrentUser.getUser()+"]"+CurrentUser.getUserRealName()+"于"+
                DateUtils.dateTimeNow("yyyy-MM-dd")+"发起"+procName);//流程主题
        draftVO.setFormNo(formNoId);//业务表单ID
        draftVO.setLastDueTime(DateUtils.dateTimeNow("yyyy-MM-dd'T'HH:mm:ss"));//要求完成期限
        draftVO.setMergeTask(isMergeTask);//是否合并任务
        draftVO.setProcInstID("0");//流程实例ID  发起流程时默认为0
        draftVO.setProcSetID(procSetId);//流程集ID
        draftVO.setProcessFullName(fullName);//流程名称
        draftVO.setProcessName(procName);//流程名称
        draftVO.setProcessStartTime(DateUtils.dateTimeNow("yyyy-MM-dd'T'HH:mm:ss"));//流程发起时间
        draftVO.setRequestId(null);
        draftVO.setSenderUserAccent(CurrentUser.getUser());//提交人工号
        draftVO.setSlotCount(slotCount);//会签规则
        draftVO.setSourceActMetaData(sourceAct);//发起环节编号
        draftVO.setStartDept("");//发起人部门编号
        draftVO.setStartTime(DateUtils.dateTimeNow("yyyy-MM-dd'T'HH:mm:ss"));//使用流程发起时间
        draftVO.setStartUser(CurrentUser.getUser());//发起人员工号
        draftVO.setStartUserCN(CurrentUser.getUserRealName());//发起人中文名称
        draftVO.setTargetActMetaData(targetAct);//目标环节编号
        draftVO.setTenantId("");//
        draftVO.setUpdateTime(new Date());//
        draftVO.setUpdateTimeEnd(new Date());//
//        draftVO.setUserChsName(nextDealerNameList.get(0));//待处理人中文名称
        draftVO.setUserChsName(org.apache.commons.lang.StringUtils.join(nextDealerNameList,","));

        //调用远程接口
        result = restClient.postCgnVoForRest(url,header,draftVO);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 查询流程节点的基本信息  是为了了解 会签规则  是否重选快速审批人
     * 参数说明 paramsMap
     * 返回值说明:
     ***********************************/
    public ApiResult getBpmPscActInfo(Map paramsMap) throws Exception{
        String actId = paramsMap.get("actId").toString();

        if("local".equals(devMode)) {
//            String json = "{\n" +
//                    "  \"responseId\": \"1\",\n" +
//                    "  \"code\": \"200\",\n" +
//                    "  \"msg\": \"成功\",\n" +
//                    "  \"data\": {\n" +
//                    "    \"actUuid\": \"5af512ce9b30df67bf05c4984cba64db\",\n" +
//                    "    \"actId\": 76780,\n" +
//                    "    \"procId\": 5810,\n" +
//                    "    \"actName\": \"020_审批信息\",\n" +
//                    "    \"actMetadata\": \"020\",\n" +
//                    "    \"taskActType\": 1,\n" +
//                    "    \"taskProcessRule\": 1,\n" +
//                    "    \"isMergeTask\": 1,\n" +
//                    "    \"processGroups\": null,\n" +
//                    "    \"processFilters\": null,\n" +
//                    "    \"reSignType\": \"1\",\n" +
//                    "    \"tenantId\": \"1\",\n" +
//                    "    \"isFastDeal\": \"1\",\n" +
//                    "    \"isReselFastDealer\": \"0\"\n" +
//                    "  }\n" +
//                    "}";
//            return JacksonUtil.readValue(json,ApiResult.class);
            List list = new ArrayList();
            list.add(paramsMap);
            ApiResult invoke = mockClient.invoke("bpmCenterServiceImpl", "getBpmPscActInfo", list, ApiResult.class,Map.class);
            return invoke;
        }

        String realServiceUrl = Constants.BPMCENTER_URL + "/getBpmPscActInfo";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;
        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);
        //调用远程接口
        result = restClient.postCgnVoForRest(url,header,actId);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }

    /**********************************
     * 用途说明: 获取上一审批信息 通过查询某个流程实例的已办 这里没有分页请注意性能 psc pageSize 不超过100
     * 参数说明 paramsMap
     * 返回值说明:
     ***********************************/
    @Override
    public HashMap getLasApproveInfo(Map paramsMap) throws Exception {
        String procInstId = paramsMap.get("procInsId").toString();

        String realServiceUrl = Constants.BPMCENTER_URL + "/getworklistitemlogbyprocinstid";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;
        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);
        //条件参数
        WorkListItemLogByProcInstVO procInstVO = new WorkListItemLogByProcInstVO();
        procInstVO.setRequestConditionVO(requestConditionVO);
        procInstVO.setPid(Integer.parseInt(procInstId));

        if("local".equals(devMode)) {
//            String json = "{\n" +
//                    "    \"responseId\": \"1\",\n" +
//                    "    \"code\": \"200\",\n" +
//                    "    \"msg\": \"成功\",\n" +
//                    "    \"data\": [{\n" +
//                    "            \"appCode\": null,\n" +
//                    "            \"operationType\": 0,\n" +
//                    "            \"procInstID\": 80554,\n" +
//                    "            \"approveAccount\": \"PXMWRYA\",\n" +
//                    "            \"approveActID\": 76779,\n" +
//                    "            \"approveActMetaData\": \"010\",\n" +
//                    "            \"approveActName\": \"010_填写信息\",\n" +
//                    "            \"approveChsName\": \"阮洋\",\n" +
//                    "            \"approveDeptID\": \"\",\n" +
//                    "            \"approveWorkID\": 0,\n" +
//                    "            \"delegatedAccount\": \"\",\n" +
//                    "            \"delegatedChsName\": \"\",\n" +
//                    "            \"delegatedDeptID\": \"\",\n" +
//                    "            \"endDateTime\": \"2019-11-29 10:00:35\",\n" +
//                    "            \"isDelegated\": false,\n" +
//                    "            \"isEnable\": false,\n" +
//                    "            \"logID\": 309729,\n" +
//                    "            \"operationTypeText\": null,\n" +
//                    "            \"startDateTime\": \"2019-11-29 10:00:35\",\n" +
//                    "            \"comment\": \"\"\n" +
//                    "        }, {\n" +
//                    "            \"appCode\": null,\n" +
//                    "            \"operationType\": 11,\n" +
//                    "            \"procInstID\": 80554,\n" +
//                    "            \"approveAccount\": \"pxmwzyp\",\n" +
//                    "            \"approveActID\": 76780,\n" +
//                    "            \"approveActMetaData\": \"020\",\n" +
//                    "            \"approveActName\": \"020_审批信息\",\n" +
//                    "            \"approveChsName\": \"张膺鹏\",\n" +
//                    "            \"approveDeptID\": \"\",\n" +
//                    "            \"approveWorkID\": 0,\n" +
//                    "            \"delegatedAccount\": \"\",\n" +
//                    "            \"delegatedChsName\": \"\",\n" +
//                    "            \"delegatedDeptID\": \"\",\n" +
//                    "            \"endDateTime\": \"2019-11-29 10:03:32\",\n" +
//                    "            \"isDelegated\": false,\n" +
//                    "            \"isEnable\": false,\n" +
//                    "            \"logID\": 309730,\n" +
//                    "            \"operationTypeText\": null,\n" +
//                    "            \"startDateTime\": \"2019-11-29 10:03:32\",\n" +
//                    "            \"comment\": \"同意!\"\n" +
//                    "        }, {\n" +
//                    "            \"appCode\": null,\n" +
//                    "            \"operationType\": 1,\n" +
//                    "            \"procInstID\": 80554,\n" +
//                    "            \"approveAccount\": \"pxmwzyp\",\n" +
//                    "            \"approveActID\": 76780,\n" +
//                    "            \"approveActMetaData\": \"020\",\n" +
//                    "            \"approveActName\": \"020_审批信息\",\n" +
//                    "            \"approveChsName\": \"张膺鹏\",\n" +
//                    "            \"approveDeptID\": \"\",\n" +
//                    "            \"approveWorkID\": 0,\n" +
//                    "            \"delegatedAccount\": \"\",\n" +
//                    "            \"delegatedChsName\": \"\",\n" +
//                    "            \"delegatedDeptID\": \"\",\n" +
//                    "            \"endDateTime\": \"2019-11-29 10:03:32\",\n" +
//                    "            \"isDelegated\": false,\n" +
//                    "            \"isEnable\": false,\n" +
//                    "            \"logID\": 309731,\n" +
//                    "            \"operationTypeText\": null,\n" +
//                    "            \"startDateTime\": \"2019-11-29 10:03:32\",\n" +
//                    "            \"comment\": \"同意!\"\n" +
//                    "        }, {\n" +
//                    "            \"appCode\": null,\n" +
//                    "            \"operationType\": 12,\n" +
//                    "            \"procInstID\": 80554,\n" +
//                    "            \"approveAccount\": \"pxmwzyp\",\n" +
//                    "            \"approveActID\": 76780,\n" +
//                    "            \"approveActMetaData\": \"020\",\n" +
//                    "            \"approveActName\": \"020_审批信息\",\n" +
//                    "            \"approveChsName\": \"张膺鹏\",\n" +
//                    "            \"approveDeptID\": \"\",\n" +
//                    "            \"approveWorkID\": 0,\n" +
//                    "            \"delegatedAccount\": \"\",\n" +
//                    "            \"delegatedChsName\": \"\",\n" +
//                    "            \"delegatedDeptID\": \"\",\n" +
//                    "            \"endDateTime\": \"2019-11-29 10:04:31\",\n" +
//                    "            \"isDelegated\": false,\n" +
//                    "            \"isEnable\": false,\n" +
//                    "            \"logID\": 309733,\n" +
//                    "            \"operationTypeText\": null,\n" +
//                    "            \"startDateTime\": \"2019-11-29 10:04:31\",\n" +
//                    "            \"comment\": \"已阅\"\n" +
//                    "        }\n" +
//                    "    ]\n" +
//                    "}\n";
//            ApiResult apiResult = JacksonUtil.readValue(json, ApiResult.class);
//            ArrayList<HashMap> arr = (ArrayList) apiResult.getData();
//            Collections.reverse(arr);
//            //取第一个  再获取流程日志记录信息
//            return arr.get(0);
            List list = new ArrayList();
            list.add(paramsMap);
            HashMap invoke = mockClient.invoke("bpmCenterServiceImpl", "getLasApproveInfo", list, HashMap.class,Map.class);
            return invoke;
        }

        //调用远程接口
        result = restClient.postCgnVoForRest(url, header, procInstVO);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }else if(result.getData() != null){
            ArrayList<HashMap> arr = (ArrayList) result.getData();
            Collections.reverse(arr);
            //取第一个  再获取流程日志记录信息
            return arr.get(0);
        }else{
            throw new Exception(MessageUtils.message("cud.bpmcenter.noHasDoneError"));
        }
    }

    /**********************************
     * 用途说明: 获取已阅任务列表
     * 参数说明 paramsMap
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult getcopysenditemlogs(Map paramsMap) throws Exception {
        String realServiceUrl = Constants.BPMCENTER_URL + "/getcopysenditemlogs";
        String url = CgnHeader.getUrl(aepProperties.getActive()) + realServiceUrl;

        String pageIndex = paramsMap.get("pageIndex").toString();
        String pageSize = paramsMap.get("pageSize").toString();
        CgnRequestHeader header = null;
        ApiResult result = null;
        header = CgnHeader.getHeader(realServiceUrl,aepProperties);

        //传递参数
        DoneTaskQueryVO doneTaskQueryVO = new DoneTaskQueryVO();
        BpmDoneTaskQuery doneTaskQuery = new BpmDoneTaskQuery();
        doneTaskQueryVO.setRequestConditionVO(requestConditionVO);
        doneTaskQuery.setApp(appCode);
        //查询条件
        List<BpmDoneTaskFilter> filterList = new ArrayList<>();
        if(!StringUtils.isEmpty("searchType") && !paramsMap.get("searchType").toString().equals("0")){
            //说明有查询条件
            HashMap searchMap = (HashMap) paramsMap.get("searchParams");
            Set<Map.Entry> set = searchMap.entrySet();
            BpmDoneTaskFilter doneTaskFilter = new BpmDoneTaskFilter();
            Iterator<Map.Entry> it = set.iterator();
            //条件查询
            for (int i = 0; it.hasNext() ; i++) {
                Map.Entry entry = it.next();
                if(!StringUtils.isEmpty(entry.getValue()) && !entry.getValue().toString().trim().equals("")){
                    doneTaskFilter.setField(DoneTaskField.valueOf(entry.getKey().toString()));//找到字段
                    doneTaskFilter.setOperatoer(QueryOperator.Like);
                    doneTaskFilter.setValue("%"+entry.getValue().toString()+"%");//找到值
                    if (filterList.size() == 0) {
                        doneTaskFilter.setLogical(QueryLogical.Empty);
                    } else {
                        doneTaskFilter.setLogical(QueryLogical.And);
                    }
                    filterList.add(doneTaskFilter);
                    doneTaskFilter = new BpmDoneTaskFilter();
                }else{
                    //表示值为空字符串或者 null
                    doneTaskFilter = new BpmDoneTaskFilter();
                }
            }
            if (filterList.size() != 0){
                doneTaskQuery.setConditions(filterList);
            }else {
                doneTaskQuery.setConditions(null);
            }
        }else{
            doneTaskQuery.setConditions(null);
        }

        doneTaskQuery.setDirection(QueryDirection.DESC);
        doneTaskQuery.setOrderBys(Arrays.asList(DoneTaskField.StartTime));//排序
        doneTaskQuery.setImpersonateUser(CurrentUser.getUser());
        doneTaskQuery.setSqlWhereData(null);
        //翻页参数
        QueryPaging paging = new QueryPaging();
        paging.setStartPage(Integer.parseInt(pageIndex));
        paging.setPageSize(Integer.parseInt(pageSize));
        doneTaskQuery.setPageSetting(paging);
        doneTaskQueryVO.setDoneTaskQuery(doneTaskQuery);

        if("local".equals(devMode)) {
//            String json = "{\n" +
//                    "  \"responseId\": \"1\",\n" +
//                    "  \"code\": \"200\",\n" +
//                    "  \"msg\": \"成功\",\n" +
//                    "  \"data\": {\n" +
//                    "    \"resultData\": [\n" +
//                    "      {\n" +
//                    "        \"DFList\": [\n" +
//                    "          {\n" +
//                    "            \"value\": \" \",\n" +
//                    "            \"key\": \"Field1\"\n" +
//                    "          },\n" +
//                    "          {\n" +
//                    "            \"value\": \" \",\n" +
//                    "            \"key\": \"Field2\"\n" +
//                    "          },\n" +
//                    "          {\n" +
//                    "            \"value\": \" \",\n" +
//                    "            \"key\": \"Field3\"\n" +
//                    "          },\n" +
//                    "          {\n" +
//                    "            \"value\": \" \",\n" +
//                    "            \"key\": \"Field4\"\n" +
//                    "          },\n" +
//                    "          {\n" +
//                    "            \"value\": \" \",\n" +
//                    "            \"key\": \"Field5\"\n" +
//                    "          },\n" +
//                    "          {\n" +
//                    "            \"value\": \" \",\n" +
//                    "            \"key\": \"Field6\"\n" +
//                    "          }\n" +
//                    "        ],\n" +
//                    "        \"startDept\": \"\",\n" +
//                    "        \"actMetaData\": \"020\",\n" +
//                    "        \"procInstID\": \"79348\",\n" +
//                    "        \"actName\": \"020_审批信息\",\n" +
//                    "        \"processName\": \"兑奖流程\",\n" +
//                    "        \"startTime\": \"2019/10/28 11:29:36\",\n" +
//                    "        \"startUser\": \"PXMWRYA\",\n" +
//                    "        \"processFullName\": \"BMWS\\\\TestProcess\",\n" +
//                    "        \"fromNO\": \"715a08bf2db74ab19ca72182ae32eec0\",\n" +
//                    "        \"actID\": \"11115\",\n" +
//                    "        \"appTaskTitle\": \"\",\n" +
//                    "        \"procID\": \"1116\",\n" +
//                    "        \"approveWorkID\": \"371018\",\n" +
//                    "        \"startCNUser\": \"阮洋\",\n" +
//                    "        \"priority\": \"-1\",\n" +
//                    "        \"appTaskID\": \"\",\n" +
//                    "        \"lastDueTime\": {\n" +
//                    "          \"date\": 1,\n" +
//                    "          \"hours\": 0,\n" +
//                    "          \"seconds\": 0,\n" +
//                    "          \"month\": 0,\n" +
//                    "          \"timezoneOffset\": -480,\n" +
//                    "          \"year\": -1899,\n" +
//                    "          \"minutes\": 0,\n" +
//                    "          \"time\": -62135798400000,\n" +
//                    "          \"day\": 6\n" +
//                    "        },\n" +
//                    "        \"procGuid\": \"203a251610f944de84b3dd376735187f\",\n" +
//                    "        \"approveDeptID\": \"\",\n" +
//                    "        \"folio\": \"关于测试获奖的流程\",\n" +
//                    "        \"finishDate\": \"2019/10/28 11:32:40\",\n" +
//                    "        \"endTime\": \"2019/10/28 11:29:37\",\n" +
//                    "        \"procSetID\": \"463\",\n" +
//                    "        \"status\": \"运行中\"\n" +
//                    "      }\n" +
//                    "    ],\n" +
//                    "    \"page\": {\n" +
//                    "      \"startPage\": 1,\n" +
//                    "      \"totalPage\": 0,\n" +
//                    "      \"pageSize\": 1,\n" +
//                    "      \"totalCount\": 15\n" +
//                    "    }\n" +
//                    "  }\n" +
//                    "}";
//            return JacksonUtil.readValue(json,ApiResult.class);
            List list = new ArrayList();
            list.add(paramsMap);
            ApiResult invoke = mockClient.invoke("bpmCenterServiceImpl", "getcopysenditemlogs", list, ApiResult.class,Map.class);
            return invoke;
        }

        //调用远程接口
        result = restClient.postCgnVoForRest(url, header, doneTaskQueryVO);
        if(!CODE.equals(result.getCode())){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",result.getMsg()));
        }
        return result;
    }


//    public User  setPscUser(String account, String taskId, String taskTitle, String deptId,
//                            String isHidden, String isMobile, String isRenew, String isUserNotify,
//                            String lastDueTime, String oldActInstDest, String operationType,
//                            String senderUserAccent, String senderUserDeptId, String snGroup,
//                            String startTime, String userChsName){
//        User u = new User();
//        u.setAccount(account);
//        u.setAppTaskID(taskId);
//        u.setAppTaskTitle(taskTitle);
//        u.setDeptID(deptId);
//        u.setIsHidden(isHidden);
//        u.setIsMobile(isMobile);
//        u.setIsRenew(isRenew);
//        u.setIsUserNotify(isUserNotify);
//        u.setLastDueTime(lastDueTime);
//        u.setOldActInstDest(oldActInstDest);
//        u.setOperationType(operationType);
//        u.setSenderUserAccent(senderUserAccent);
//        u.setSenderUserDeptID(senderUserDeptId);
//        u.setSnGroup(snGroup);
//        u.setStartTime(startTime);
//        u.setUserChsName(userChsName);
//        return u;
//    }

    /**********************************
     * 用途说明: 设置psc的routeinfo对象
     * 参数说明 procInstId
     * 参数说明 routes
     * 参数说明 lineRuleIsFirst
     * 参数说明 isRouteNotify
     * 返回值说明:
     ***********************************/
    public RouteInfo setPscRouteInfo(String procInstId,Route[] routes,String lineRuleIsFirst,
                                     String isRouteNotify){
        RouteInfo routeInfo = new RouteInfo();
        routeInfo.setProcInstID(procInstId);
        routeInfo.setRoutes(routes);
        routeInfo.setLineRuleIsFirst(lineRuleIsFirst);
        routeInfo.setIsRouteNotify(isRouteNotify);
        return routeInfo;
    }

    /**********************************
     * 用途说明: 设置psc的route对象
     * 参数说明 guidCode
     * 参数说明 sourceActMetaData
     * 参数说明 targetActMetaData
     * 参数说明 impersonateUser
     * 参数说明 currentStep
     * 参数说明 isActNotify
     * 参数说明 snGroup
     * 参数说明 steps
     * 返回值说明:
     ***********************************/
    public Route setPscRoute(String guidCode, String sourceActMetaData, String targetActMetaData,
                             String impersonateUser, String currentStep,String isActNotify,
                             String snGroup,Step[] steps){
        Route route = new Route();
        route.setGuidCode(guidCode);
        route.setSourceActMetaData(sourceActMetaData);
        route.setTargetActMetaData(targetActMetaData);
        route.setImpersonateUser(impersonateUser);
        route.setCurrentStep(currentStep);
        route.setIsActNotify(isActNotify);
        route.setSnGroup(snGroup);
        route.setSteps(steps);
        return route;
    }

    /**********************************
     * 用途说明: 设置psc的step对象
     * 参数说明 slotCount
     * 参数说明 slotGuid
     * 参数说明 actApproveGuid
     * 参数说明 mergeTask
     * 参数说明 users
     * 返回值说明:
     ***********************************/
    public Step setPscStep(String slotCount, String slotGuid, String actApproveGuid,
                           String mergeTask, User[] users){
        Step step = new Step();
        step.setSlotCount(slotCount);
        step.setSlotGuid(slotGuid);
        step.setActApproveGuid(actApproveGuid);
        step.setMergeTask(mergeTask);
        step.setUsers(users);
        return step;
    }

    /**********************************
     * 用途说明: 日期类型转换
     *  2019-05-30T11:00:00  不加T 发起流程提示 类型报错   T代表开始时间  Z代表时区
     * 参数说明 d
     * 返回值说明:
     ***********************************/
    public String transDate(Date d){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        String date = format.format(d);
        return date;
    }

}